cclabelttf 描边是如何实现的?其本质?

[转载]CCLabelTTF,label.color&=&ccc3
我现在有一句话&&
人名+动作名称+数量名称
例如&&小明收走了5个桃子
“小明”需要蓝色的字体&&“收走了”需要中色的字体&&“5”
需要红色字体&&“桃子”需要中色字体
我的问题就是,在一个label中怎么设置这三种颜色。
或者要是没办法的话 ,我就只能用很笨的方法 去创建三个label呢???
CGSize winSize = [[CCDirector sharedDirector] winSize];
&&&&CGSize
&&&&CGPoint
&&&&CCLabelTTF
= [CCLabelTTF labelWithString:personName fontName:@"Arial"
fontSize:16];
&&&&label.color
= ccc3(65, 121, 183);
addChild:label];
&&&&label.anchorPoint
= *****(0,0);
= label.position =
*****(par.contentSize.width/2-140,par.contentSize.height/2 +
= label.contentS
= [CCLabelTTF labelWithString:@"从这里拿走了" fontName:@"Arial"
fontSize:16];
&&&&//NSLog(@"size
w:%f",size.width);
&&&&label.color
= ccc3(142,57,0);
addChild:label];
&&&&label.anchorPoint
= *****(0,0);
= label.position = *****(pos.x + size.width+2,winSize.height/2 +
= label.contentS
= [CCLabelTTF labelWithString:[NSString
stringWithFormat:@"%d",count] fontName:@"Arial" fontSize:16];
&&&&label.color
= ccc3(188,0,0);
addChild:label];
&&&&label.anchorPoint
= *****(0,0);
= label.position = *****(pos.x + size.width+2,winSize.height/2 +
= label.contentS
= [CCLabelTTF labelWithString:@"个" fontName:@"Arial"
fontSize:16];
&&&&label.color
= ccc3(142,57,0);
addChild:label];
&&&&label.anchorPoint
= *****(0,0);
= label.position = *****(pos.x + size.width,winSize.height/2 +
= label.contentS
= [CCLabelTTF labelWithString:[NSString
stringWithFormat:@"%@。",article] fontName:@"Arial"
fontSize:16];
&&&&label.color
= ccc3(47,144,0);
addChild:label];
&&&&label.anchorPoint
= *****(0,0);
= label.position = *****(pos.x + size.width+2,winSize.height/2 +
= label.contentS
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。下次自动登录
现在的位置:
& 综合 & 正文
Cocos2d—X游戏开发之 CCLabelTTF 标签详解和对齐方式设置(分数显示)(十六)
在Cocos2d—X游戏开发中,CCLabelTTF 和 CCSprite 大概是使用最多的2个类了。标签主要用于显示静态文本,可以设置字体的大小和位置等属性。
现在,我们先来看下CCLabelTTF 的基本源码。
S1,从下面的可以看到 CCLabelTTF 继承于 CCSprite 和 CCLabeProtocol 。
class CC_DLL CCLabelTTF : public CCSprite, public CCLabelProtocol
CCLabelTTF();
virtual ~CCLabelTTF();
const char* description();
/** creates a CCLabelTTF with a font name and font size in points
@since v2.0.1
使用最多的创建标签的方法
static CCLabelTTF * create(const char *string, const char *fontName, float fontSize);
/** creates a CCLabelTTF from a fontname, horizontal alignment, dimension in points,
and font size in points.
@since v2.0.1
static CCLabelTTF * create(const char *string, const char *fontName, float fontSize,
const CCSize& dimensions, CCTextAlignment hAlignment);
/** creates a CCLabel from a fontname, alignment, dimension in points and font size in points
@since v2.0.1
static CCLabelTTF * create(const char *string, const char *fontName, float fontSize,
const CCSize& dimensions, CCTextAlignment hAlignment,
CCVerticalTextAlignment vAlignment);
/** Create a lable with string and a font definition*/
static CCLabelTTF * createWithFontDefinition(const char *string, ccFontDefinition &textDefinition);
/** initializes the CCLabelTTF with a font name and font size */
bool initWithString(const char *string, const char *fontName, float fontSize);
/** initializes the CCLabelTTF with a font name, alignment, dimension and font size */
bool initWithString(const char *string, const char *fontName, float fontSize,
const CCSize& dimensions, CCTextAlignment hAlignment);
/** initializes the CCLabelTTF with a font name, alignment, dimension and font size */
bool initWithString(const char *string, const char *fontName, float fontSize,
const CCSize& dimensions, CCTextAlignment hAlignment,
CCVerticalTextAlignment vAlignment);
/** initializes the CCLabelTTF with a font name, alignment, dimension and font size */
bool initWithStringAndTextDefinition(const char *string, ccFontDefinition &textDefinition);
/** set the text definition used by this label */
void setTextDefinition(ccFontDefinition *theDefinition);
/** get the text definition used by this label */
ccFontDefinition * getTextDefinition();
/** enable or disable shadow for the label */
void enableShadow(const CCSize &shadowOffset, float shadowOpacity, float shadowBlur, bool mustUpdateTexture = true);
/** disable shadow rendering */
void disableShadow(bool mustUpdateTexture = true);
/** enable or disable stroke */
void enableStroke(const ccColor3B &strokeColor, float strokeSize, bool mustUpdateTexture = true);
/** disable stroke */
void disableStroke(bool mustUpdateTexture = true);
/** set text tinting */
void setFontFillColor(const ccColor3B &tintColor, bool mustUpdateTexture = true);
/** initializes the CCLabelTTF */
bool init();
/** Creates an label.
static CCLabelTTF * create();
/** changes the string to render
* @warning Changing the string is as expensive as creating a new CCLabelTTF. To obtain better performance use CCLabelAtlas
virtual void setString(const char *label);
//设置标签文字内容的一对方法,当标签内容需要时时变化时,就是它了
virtual const char* getString(void);
CCTextAlignment getHorizontalAlignment();
void setHorizontalAlignment(CCTextAlignment alignment);
//当标签文字变化时,位置可能不如意,这时需要它设置对齐方式,横向
CCVerticalTextAlignment getVerticalAlignment();
void setVerticalAlignment(CCVerticalTextAlignment verticalAlignment);
//标签纵向对齐方式设置
CCSize getDimensions();
void setDimensions(const CCSize &dim);
float getFontSize();
void setFontSize(float fontSize);
const char* getFontName();
void setFontName(const char *fontName);
bool updateTexture();
protected:
/** set the text definition for this label */
_updateWithTextDefinition(ccFontDefinition & textDefinition, bool mustUpdateTexture = true);
ccFontDefinition
_prepareTextDefinition(bool adjustForResolution = false);
/** Dimensions of the label in Points */
CCSize m_tD
/** The alignment of the label */
CCTextAlignment
/** The vertical alignment of the label */
CCVerticalTextAlignment m_vA
/** Font name used in the label */
std::string * m_pFontN
/** Font size of the label */
float m_fFontS
/** label's string */
std::string m_
/** font shadow */
/** font stroke */
/** font tint */
m_textFillC
好的,现在我们来看下CCTextAlignment的定义,是2个枚举类型。
typedef enum
kCCVerticalTextAlignmentTop,
kCCVerticalTextAlignmentCenter,
kCCVerticalTextAlignmentBottom,
} CCVerticalTextA
typedef enum
kCCTextAlignmentLeft,
kCCTextAlignmentCenter,
kCCTextAlignmentRight,
S2,现在来看这个CCLabelTTF的一个小Demo。
//获取主屏幕的尺寸
CCSize winSize = CCDirector::sharedDirector()-&getWinSize();
//创建标签
CCLabelTTF *label = CCLabelTTF::create("Hello CCLabelTTF", "Arial", 24);
//设置标签文字颜色
label-&setColor(ccc3(0,0,0));
//设置标签位置
label-&setPosition(ccp(winSize.width/2,winSize.height/2));
//设置锚点为左下角
label-&setAnchorPoint(CCPointZero);
//设置标签的横向对齐方式为向左对齐,这样标签内容增加,只会向右增加
label-&setHorizontalAlignment(kCCTextAlignmentLeft);
//添加为子节点
this-&addChild(label,1);
这样设置对齐方式后,标签内容在修改,始终向左对齐,贴图如下:
&&&&推荐文章:
【上篇】【下篇】CCLabelTTF、CCLabelAtlas和CCLabelBMFont的区别 - Bill Yuan - 博客园
在Cocos2d以及Cocos2d-x中,我们经常会用到CCLabelTTF以及CCLabelAtlas在层或精灵中添加文字。
其实总共有三个添加文字的类,另外一个是CCLabelBMFont,我用的不怎么多。
1. CCLabelTTF
CCLabelTTF::labelWithString(const char *label,
//文字内容
const CCSize& dimensions,
//范围 CCSize(0,0)默认大小
CCTextAlignment alignment,
//对齐方式 0左 1中 2右
const char *fontName,
float fontSize
CCLabelTTF是CCTextureNode的子类,通过系统字体生成label。
CCLabelTTF对象渲染比较慢,每次调用setString的时候,一个新的OpenGL纹理将被创建,这意味着setString和创建一个新的标签一样慢,所以当需要频繁更新label的时候,应该选择另外两种文字类。
由于CCLabelTTF这个类使用的是系统中的字体,不需要额外往项目文件中添加字体文件。但如果你有自定义的字体也可以加到项目中,如果无法使用,可以查看一下ccConfig.h中的CC_FONT_LABEL_SUPPORT是否enable了。
2. CCLabelAtlas
CCLabelAtlas::labelWithString(const char *label,
//标签文字内容
const char *charMapFile,
//图片路径
unsigned int itemWidth,
//元素的宽度
int unsigned itemHeight,
unsigned char startCharMap //起始的字符)
引擎模板里面左下角显示帧率的数字,就是利用CCLabelAtlas来实现的。因为帧率一直在变。
每个字符的高度和宽度不能设置错误,否则显示的时候可能就不对了。最后一个起始的字符用来对应字符和图像的关系的。
3. CCLabelBMFont
CCLabelBMFont::labelWithString(const char *str,
const char *fntFile)
它是CCSpriteSheet的一个子类,对每一个字符就像一个CCSprite来对待,因此每个单独的字符可以进行旋转、缩放、设置透明等操作。
所有字符都是使用anchorPoint(0.5, 0.5),所以最好不要更改它,会影响渲染。
使用该类之前,需要添加好字体文件,包括一个图片文件(AA.png)和一个字体坐标文件(AA.fnt)。两个文件的名称相同,只是扩展名不同。
CCLabelBMFont的改变相当于每次只改变图片坐标。
随笔 - 684前几天发过一篇文章说如何实现wp8下的CCLabelTTF如何自动换行,后来发现果如预料的那般,效果很不好,主要是非等宽字体的情况下看着很糟心,因此再修改了一版,效果要好很多了。
具体实现其实就是参考initGlyphs,但是会不断的检查是否超过宽度,如果超过则自动换行。
具体的直接看代码就明白了
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
Copyright (c) Microsoft Open Technologies, Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the &Software&), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED &AS IS&, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __PLATFORM_WINRT_FREETYPE_H__
#define __PLATFORM_WINRT_FREETYPE_H__
#include &platform/CCCommon.h&
#include &platform/CCImage.h&
#include &string&
#include &vector&
#include &memory&
#define generic GenericFromFreeTypeLibrary
#define internal InternalFromFreeTypeLibrary
#include &ft2build.h&
#include &freetype/freetype.h&
#include &freetype/ftglyph.h&
#include &freetype/ftoutln.h&
#include &freetype/fttrigon.h&
#undef generic
#undef internal
NS_CC_BEGIN
typedef struct TGlyph_
// glyph index
// glyph origin on the baseline
// glyph image
} TGlyph, *PG
typedef struct FontBufferInfo
unsigned char*
} FontBufferI
typedef struct FTWordInfo
std::vector&TGlyph& // glyphs for the word
// bounding box containing all of the glyphs in the word
typedef struct FTLineInfo
std::vector&TGlyph&
// glyphs for the line text
// bounding box containing all of the glyphs in the line
// width of the line
// current pen position
class CC_DLL CCFreeTypeFont
CCFreeTypeFont();
~CCFreeTypeFont();
bool initWithString(
const char* pText,
const char* pFontName,
unsigned char* getBitmap(
CCImage::ETextAlign eAlignMask,
int* outWidth,
int* outHeight
unsigned char* loadFont(const char *pFontName, unsigned long *size);
unsigned char* CCFreeTypeFont::loadSystemFont(const char *pFontName, unsigned long *size);
FT_Error CCFreeTypeFont::initGlyphs(const char* text);
void compute_bbox(std::vector&TGlyph&& glyphs, FT_BBox
void drawText(FTLineInfo* pInfo, unsigned char* pBuffer, FT_Vector *pen);
void draw_bitmap(unsigned char* pBuffer, FT_Bitmap*
bitmap,FT_Int x,FT_Int y);
void reset();
FT_Vector getPenForAlignment(FTLineInfo* pInfo, CCImage::ETextAlign eAlignMask, int lineNumber, int totalLines);
FT_Error addLine(const std::string& line);
void newLine();
void endLine();
const std::string m_
std::string
std::string
std::vector&FTLineInfo*& m_
// requested width of text box
// requested height of text box
// final bitMap width
// final bitMap height
// width of text text after word wrapping and line breaks
// height of text text after word wrapping and line breaks
// height of a line for the font size
// the width of the window
FTLineInfo*
m_currentL
// the current line object to add words to.
/****************************************************************************
Copyright (c) 2013
cocos2d-x.org
http://cocos2d-x.org
Copyright (c) Microsoft Open Technologies, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the &Software&), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED &AS IS&, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include &CCFreeTypeFont.h&
#include &CCDirector.h&
#include &platform/CCFileUtils.h&
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8)
#include &dwrite.h&
#include &map&
#include &string&
#include &sstream&
#include &vector&
#include &memory&
#include &algorithm&
NS_CC_BEGIN
static map&std::string, FontBufferInfo& s_fontsN
static FT_Library s_FreeTypeLibrary =
CCFreeTypeFont::CCFreeTypeFont()
:m_space(& &)
, m_face(nullptr)
CCFreeTypeFont::~CCFreeTypeFont()
void CCFreeTypeFont::reset()
for(auto line:m_lines)
line-&glyphs.clear();
m_lines.clear();
if(m_face)
FT_Done_Face(m_face);
bool CCFreeTypeFont::initWithString(
const char* pText,
const char* pFontName,
inHeight )
FT_Error error = 0;
unsigned long size = 0;
unsigned char* pBuffer =
unsigned char* data =
CCSize winSize = CCDirector::sharedDirector()-&getWinSizeInPixels();
m_windowWidth = (int)winSize.
m_inWidth = inW
m_inHeight = inH
// check the cache for the font file buffer
auto ittFontNames = s_fontsNames.find(pFontName);
if(ittFontNames != s_fontsNames.end())
pBuffer = ittFontNames-&second.pB
size = ittFontNames-&second.
#endif // 0
if(!pBuffer)
// attempt to load font from Resources fonts folder
pBuffer = loadFont(pFontName, &size);
if(!pBuffer)
// attempt to load font from System fonts folder
pBuffer = loadSystemFont(pFontName, &size);
if(!pBuffer)
// attempt to load default font from Resources fonts folder
pBuffer = loadFont(&Arial&, &size);
if(!pBuffer)
// attempt to load default font from System fonts folder
pBuffer = loadSystemFont(&Arial&, &size);
if(!pBuffer) // font not found!
// cache the font file buffer
FontBufferI
info.pBuffer = pB
info.size =
s_fontsNames[pFontName]=
#endif // 0
m_fontName = pFontN
m_text = pT
if(!s_FreeTypeLibrary)
error = FT_Init_FreeType(&s_FreeTypeLibrary);
if(!error && !m_face)
error = FT_New_Memory_Face(s_FreeTypeLibrary, pBuffer, size, 0, &m_face);
if(!error)
error = FT_Select_Charmap(m_face, FT_ENCODING_UNICODE);
if(!error)
error = FT_Set_Char_Size(m_face,nSize&&6,nSize&&6,72,72);
if(!error)
error = initGlyphs(pText);
delete [] pB
return error == 0;
unsigned char* CCFreeTypeFont::getBitmap(CCImage::ETextAlign eAlignMask, int* outWidth, int* outHeight)
int lineNumber = 0;
int totalLines = m_lines.size();
m_width = m_inWidth ? m_inWidth : m_textW
m_height = m_inHeight ? m_inHeight : m_textH
unsigned int size = m_width * m_height * 4;
unsigned char* pBuffer = new unsigned char[size];
if(!pBuffer)
memset(pBuffer, 0, size);
for (auto line = m_lines.begin() ; line != m_lines.end(); ++line)
FT_Vector pen = getPenForAlignment(*line, eAlignMask, lineNumber, totalLines);
drawText(*line, pBuffer, &pen);
lineNumber++;
*outWidth = m_
*outHeight = m_
FT_Vector CCFreeTypeFont::getPenForAlignment(FTLineInfo* pInfo, CCImage::ETextAlign eAlignMask,int lineNumber, int totalLines)
FT_Error error = 0;
int stringWidth
= pInfo-&bbox.xMax - pInfo-&bbox.xM
int maxLineNumber = totalLines - 1;
pen.x = 0;
pen.y = 0;
switch(eAlignMask)
case CCImage::ETextAlign::kAlignTop: // Horizontal center and vertical top.
pen.x = ((m_width
- stringWidth) / 2) - pInfo-&bbox.xM
pen.y = pInfo-&bbox.yMax + (lineNumber * m_lineHeight);
case CCImage::ETextAlign::kAlignTopLeft: // Horizontal left and vertical top.
pen.x -=pInfo-&bbox.xM
pen.y = pInfo-&bbox.yMax + (lineNumber * m_lineHeight);
case CCImage::ETextAlign::kAlignTopRight: // Horizontal right and vertical top.
pen.x = m_width - stringWidth - pInfo-&bbox.xM
pen.y = pInfo-&bbox.yMax + (lineNumber * m_lineHeight);
case CCImage::ETextAlign::kAlignBottomRight: // Horizontal right and vertical bottom.
pen.x = m_width - stringWidth - pInfo-&bbox.xM
pen.y = m_height + pInfo-&bbox.yMin - ((maxLineNumber - lineNumber) * m_lineHeight);
case CCImage::ETextAlign::kAlignBottom: // Horizontal center and vertical bottom.
pen.x = ((m_width
- stringWidth) / 2) - pInfo-&bbox.xM
pen.y = m_height + pInfo-&bbox.yMin - ((maxLineNumber - lineNumber) * m_lineHeight);
case CCImage::ETextAlign::kAlignBottomLeft: // Horizontal left and vertical bottom.
pen.x -=pInfo-&bbox.xM
top = (m_height - m_textHeight) / 2;
pen.y = m_height + pInfo-&bbox.yMin - ((maxLineNumber - lineNumber) * m_lineHeight);
case CCImage::ETextAlign::kAlignCenter: // Horizontal center and vertical center
pen.x = ((m_width
- stringWidth) / 2) - pInfo-&bbox.xM
top = (m_height - m_textHeight) / 2;
pen.y = top + (lineNumber * m_lineHeight) + pInfo-&bbox.yM
case CCImage::ETextAlign::kAlignRight: // Horizontal right and vertical center.
pen.x = m_width - stringWidth - pInfo-&bbox.xM
top = (m_height - m_textHeight) / 2;
pen.y = top + (lineNumber * m_lineHeight) + pInfo-&bbox.yM
case CCImage::ETextAlign::kAlignLeft: // Horizontal left and vertical center.
pen.x -=pInfo-&bbox.xM
top = (m_height - m_textHeight) / 2;
pen.y = top + (lineNumber * m_lineHeight) + pInfo-&bbox.yM
CCFreeTypeFont::drawText(FTLineInfo* pInfo, unsigned char* pBuffer, FT_Vector *pen)
auto glyphs = pInfo-&
for (auto glyph = glyphs.begin() ; glyph != glyphs.end(); ++glyph)
FT_Glyph image = glyph-&
FT_Error error = FT_Glyph_To_Bitmap(&image, FT_RENDER_MODE_NORMAL, 0, 1);
if (!error)
FT_BitmapGlyph
bit = (FT_BitmapGlyph)
draw_bitmap(pBuffer, &bit-&bitmap, pen-&x + glyph-&pos.x + bit-&left,pen-&y - bit-&top);
FT_Done_Glyph(image);
void CCFreeTypeFont::draw_bitmap(unsigned char* pBuffer, FT_Bitmap*
bitmap, FT_Int x, FT_Int y)
x_max = x + bitmap-&
y_max = y + bitmap-&
for (i = x, p = 0; i & x_ i++, p++)
for ( j = y, q = 0; j & y_ j++, q++ )
if (i & 0 || j & 0 || i &= m_width || j &= m_height)
unsigned char value =
bitmap-&buffer[q * bitmap-&width + p];
if(value & 0)
FT_Int index = (j * m_width * 4) + (i * 4);
pBuffer[index++] = 0
pBuffer[index++] = 0
pBuffer[index++] = 0
pBuffer[index++] =
void CCFreeTypeFont::endLine()
if(m_currentLine)
m_lines.push_back(m_currentLine);
compute_bbox(m_currentLine-&glyphs, &m_currentLine-&bbox);
m_currentLine-&width = m_currentLine-&bbox.xMax - m_currentLine-&bbox.xM
m_textWidth = max(m_textWidth,m_currentLine-&bbox.xMax - m_currentLine-&bbox.xMin);
m_textHeight += m_lineH
m_currentLine = NULL;
void CCFreeTypeFont::newLine()
m_currentLine = new FTLineInfo();
m_currentLine-&width = 0;
m_currentLine-&pen.x = 0;
m_currentLine-&pen.y = 0;
FT_Error CCFreeTypeFont::addLine(const std::string& line)
pwszBuffer =
int num_chars = line.size();
int nBufLen = num_chars + 1;
pwszBuffer = new wchar_t[nBufLen];
if (!pwszBuffer)
return -1;
memset(pwszBuffer, 0, nBufLen);
num_chars = MultiByteToWideChar(CP_UTF8, 0, line.c_str(), num_chars, pwszBuffer, nBufLen);
pwszBuffer[num_chars] = '\0';
int maxWidth = m_inWidth ? m_inWidth : m_windowW
newLine();
FT_Vector pen = m_currentLine-&
FT_GlyphSlot
slot = m_face-&
previous = 0;
error = 0;
unsigned int
numGlyphs = 0;
FT_Bool useKerning = FT_HAS_KERNING(m_face);
int n = 0;
while (n & num_chars)
/* convert character code to glyph index */
FT_ULong c = pwszBuffer[n++];
glyph_index = FT_Get_Char_Index(m_face, c);
if (useKerning && previous && glyph_index)
FT_Get_Kerning(m_face, previous, glyph_index,
FT_KERNING_DEFAULT, &delta);
pen.x += delta.x && 6;
/* store current pen position */
glyph.pos =
glyph.index = glyph_
/* load glyph image into the slot without rendering */
error = FT_Load_Glyph(m_face, glyph_index, FT_LOAD_DEFAULT);
if (error)
/* ignore errors, jump to next glyph */
/* extract glyph image and store it in our table */
error = FT_Get_Glyph(m_face-&glyph, &glyph.image);
if (error)
/* ignore errors, jump to next glyph */
/* translate the glyph image now */
FT_Glyph_Transform(glyph.image, 0, &glyph.pos);
/* increment pen position */
pen.x += slot-&advance.x && 6;
if (pen.x & maxWidth)
m_currentLine-&pen =
endLine();
newLine();
pen = m_currentLine-&
previous = 0;
m_currentLine-&glyphs.push_back(glyph);
/* record current glyph index */
previous = glyph_
if (m_currentLine)
m_currentLine-&pen =
endLine();
CC_SAFE_DELETE_ARRAY(pwszBuffer);
FT_Error CCFreeTypeFont::initGlyphs(const char* text)
FT_Error error = 0;
std::stringstream stringStream(text);
m_textWidth = 0;
m_textHeight = 0;
// the height of a line of text based on the max height of a glyph in the font size
m_lineHeight = ((m_face-&size-&metrics.ascender) && 6) - ((m_face-&size-&metrics.descender) && 6);
m_lines.clear();
while(std::getline(stringStream, line) && !error)
addLine(line);
CCFreeTypeFont::compute_bbox(std::vector&TGlyph&& glyphs, FT_BBox
FT_BBox glyph_
/* initialize string bbox to &empty& values */
bbox.xMin = 32000;
bbox.xMax = -32000;
// use the max and min values for the entire font face
bbox.yMin = (m_face-&size-&metrics.descender) && 6;
bbox.yMax = (m_face-&size-&metrics.ascender) && 6;
/* for each glyph image, compute its bounding box, */
/* translate it, and grow the string bbox
for (auto glyph = glyphs.begin() ; glyph != glyphs.end(); ++glyph)
FT_Glyph_Get_CBox(glyph-&image, ft_glyph_bbox_pixels, &glyph_bbox);
glyph_bbox.xMin += glyph-&pos.x;
glyph_bbox.xMax += glyph-&pos.x;
glyph_bbox.yMin += glyph-&pos.y;
glyph_bbox.yMax += glyph-&pos.y;
if (glyph_bbox.xMin & bbox.xMin)
bbox.xMin = glyph_bbox.xM
if (glyph_bbox.yMin & bbox.yMin)
bbox.yMin = glyph_bbox.yM
if (glyph_bbox.xMax & bbox.xMax)
bbox.xMax = glyph_bbox.xM
if (glyph_bbox.yMax & bbox.yMax)
bbox.yMax = glyph_bbox.yM
/* check that we really grew the string bbox */
if (bbox.xMin & bbox.xMax)
bbox.xMin = 0;
bbox.yMin = 0;
bbox.xMax = 0;
bbox.yMax = 0;
/* return string bbox */
unsigned char* CCFreeTypeFont::loadFont(const char *pFontName, unsigned long *size)
std::string lowerCase(pFontName);
std::string path(pFontName);
for (unsigned int i = 0; i & lowerCase.length(); ++i)
lowerCase[i] = tolower(lowerCase[i]);
if (std::string::npos == lowerCase.find(&fonts/&))
path = &fonts/&;
path += pFontN
if (std::string::npos == lowerCase.find(&.ttf&))
path += &.ttf&;
std::string fullpath
= CCFileUtils::sharedFileUtils()-&fullPathForFilename(path.c_str());
return CCFileUtils::sharedFileUtils()-&getFileData(fullpath.c_str(), &rb&, size);
unsigned char* CCFreeTypeFont::loadSystemFont(const char *pFontName, unsigned long *size)
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
std::string aName(pFontName);
unsigned char* pBuffer =
HRESULT hr = S_OK;
IDWriteFactory *writeFactory =
IDWriteFontCollection *fontCollection =
IDWriteFontFamily *fontFamily =
IDWriteFont *matchingFont =
IDWriteFontFace *fontFace =
IDWriteFontFile *fontFile =
IDWriteFontFileLoader *fontFileLoader =
IDWriteFontFileStream *fontFileStream =
std::wstring fontNameW;
const void *fontFileReferenceKey =
UINT32 fontFileReferenceKeyS
void *fragmentContext =
for (unsigned int i = 0; i & aName.length(); ++i)
aName[i] = tolower(aName[i]);
fontNameW.assign(aName.begin(), aName.end());
//create the factory
hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast&IUnknown**&(&writeFactory));
if(SUCCEEDED(hr))
//obtain the fonts owned by the machine
= writeFactory-&GetSystemFontCollection(&fontCollection, TRUE);
//get the font
if(SUCCEEDED(hr))
hr = fontCollection-&FindFamilyName(fontNameW.c_str(), &index, &exists);
if(SUCCEEDED(hr) && exists)
hr = fontCollection-&GetFontFamily(index, &fontFamily);
if(SUCCEEDED(hr))
hr = fontFamily-&GetFirstMatchingFont(DWRITE_FONT_WEIGHT_REGULAR, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL, &matchingFont);
if(SUCCEEDED(hr))
hr = matchingFont-&CreateFontFace(&fontFace);
if(SUCCEEDED(hr))
UINT32 numberOfFiles = 1;
hr = fontFace-&GetFiles(&numberOfFiles, &fontFile);
if(SUCCEEDED(hr))
//create the font file stream
hr = fontFile-&GetReferenceKey(&fontFileReferenceKey, &fontFileReferenceKeySize);
if(SUCCEEDED(hr))
hr = fontFile-&GetLoader(&fontFileLoader);
if(SUCCEEDED(hr))
hr = fontFileLoader-&CreateStreamFromKey(fontFileReferenceKey, fontFileReferenceKeySize, &fontFileStream);
if(SUCCEEDED(hr))
//finally get the font file dat
UINT64 fileS
const void *fragmentStart =
hr = fontFileStream-&GetFileSize(&fileSize);
if(SUCCEEDED(hr))
hr = fontFileStream-&ReadFileFragment(&fragmentStart, 0, fileSize, &fragmentContext);
if(SUCCEEDED(hr))
pBuffer = (unsigned char*)malloc((size_t)fileSize);
memcpy(pBuffer, fragmentStart, (size_t)fileSize);
*size = (unsigned long)fileS
//clean up all the DWrite stuff
if(fontFileStream)
fontFileStream-&ReleaseFileFragment(fragmentContext);
fontFileStream-&Release();
if(fontFileLoader)
fontFileLoader-&Release();
if(fontFile)
fontFile-&Release();
if(fontFace)
fontFace-&Release();
if(matchingFont)
matchingFont-&Release();
if(fontFamily)
fontFamily-&Release();
if(fontCollection)
fontCollection-&Release();
if(writeFactory)
writeFactory-&Release();

我要回帖

更多关于 cclabelttf 字体加粗 的文章

 

随机推荐