目錄
Description
在Cocos2d-x中,創建Label有四種方式:
系統字體:createWithSystemFont
TTF字體:createWithTTF
BMFont:createWithBMFont
CharMap:createWithCharMap
這裏記錄一下在Cocos2d-lua中創建系統字體和TTF字體Label的使用!
創建系統字體的Label
--[[
static Label* createWithSystemFont(
const std::string& text, // 顯示的文字內容
const std::string& font, // 字體文件或字體名稱
float fontSize, // 字號(> 0)
const Size& dimensions = Size::ZERO, //尺寸,寬高(高度爲0時自動換行)
TextHAlignment hAlignment = TextHAlignment::LEFT, // 水平對齊方式
TextVAlignment vAlignment = TextVAlignment::TOP // 垂直對齊方式
);
]]
local systemLabel = cc.Label:createWithSystemFont(
"PHP is the best language in the world !",
"Arial",
20,
cc.size(150, 0),
cc.TEXT_ALIGNMENT_LEFT,
cc.VERTICAL_TEXT_ALIGNMENT_TOP
)
systemLabel:setAnchorPoint(0, 1)
systemLabel:setPosition(cc.p(0, 0))
parent:addChild(systemLabel)
創建TTF字體的Label
方式1
--[[
static Label * createWithTTF(
const std::string& text,
const std::string& fontFilePath, // ttf字體文件路徑
float fontSize,
const Size& dimensions = Size::ZERO,
TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP
);
]]
local ttfLabel = cc.Label:createWithTTF(
"PHP is the best language in the world !",
"res/fontFilePath.ttf",
20,
cc.size(150, 0),
cc.TEXT_ALIGNMENT_LEFT,
cc.VERTICAL_TEXT_ALIGNMENT_TOP
)
-- ttfLabel:setDimensions(150, 0) -- 設置Label的尺寸,height爲0時自動換行
ttfLabel:setLineHeight(30) -- 設置行間距,不支持系統字體
ttfLabel:setAdditionalKerning(0) -- 設置文字間距,不支持系統字體
print("rows->", ttfLabel:getStringNumLines()) -- 獲取行數
print("height->", ttfLabel:getContentSize().height) -- 獲取Label實際的高度
ttfLabel:setAnchorPoint(0, 1)
ttfLabel:setPosition(cc.p(0, 0))
parent:addChild(ttfLabel)
方式2
--[[
// TTFConfig結構體
typedef struct _ttfConfig
{
std::string fontFilePath;
float fontSize;
GlyphCollection glyphs; // 字符集
const char *customGlyphs;
bool distanceFieldEnabled; // 是否讓字體緊湊
int outlineSize; // 描邊尺寸,描邊顏色默認爲黑色
// 構造函數
_ttfConfig(const std::string& filePath = "",float size = 12, const GlyphCollection& glyphCollection = GlyphCollection::DYNAMIC,
const char *customGlyphCollection = nullptr, bool useDistanceField = false, int outline = 0)
: fontFilePath(filePath)
, fontSize(size)
, glyphs(glyphCollection)
, customGlyphs(customGlyphCollection)
, distanceFieldEnabled(useDistanceField)
, outlineSize(outline)
{
if(outline > 0)
{
distanceFieldEnabled = false;
}
}
} TTFConfig;
static Label* createWithTTF(
const TTFConfig& ttfConfig, // TTFConfig配置
const std::string& text,
TextHAlignment hAlignment = TextHAlignment::LEFT,
int maxLineWidth = 0 // 最大行寬,用於自動換行,0表示不設置!
);
]]
local ttfConfig = {}
ttfConfig.fontFilePath = "res/fontFilePath.ttf"
ttfConfig.fontSize = 20
-- ttfConfig.outlineSize = 2
local ttfLabel = cc.Label:createWithTTF(
ttfConfig,
"PHP is the best language in the world !",
cc.TEXT_ALIGNMENT_LEFT,
150
)
ttfLabel:setTextColor(cc.c4b(255, 0, 0, 255)) -- 設置文本顏色
ttfLabel:enableOutline(cc.c4b(0, 255, 0, 255), 2) -- 設置描邊
ttfLabel:setAnchorPoint(0, 1)
ttfLabel:setPosition(cc.p(0, 0))
parent:addChild(ttfLabel)