使用CCLabelTTF的OTF字体

时间:2013-06-20 03:55:57

标签: fonts cocos2d-iphone opentype

我正在尝试将.otf字体与CCLabelTTF ...

一起使用

它不起作用。所述字体适用于原生UILabel。任何解决方法?将UILabel渲染为CCSprite-ish?将OTF转换为TTF ......似乎太麻烦了。

  • 编辑。我写了这个。我认为它有效。将会看到它如何发展。
  • 编辑2.如果您使用颜色UIColor.whiteColor创建标签,那么很酷,您可以使用mylabel.color = ccc3(0, 0, 0);设置颜色以使其变为黑色或任何其他颜色。然后,您可以使用CCTintTo
  • 自由地为文本着色

Spriteuifont.h:

#import "CCSprite.h"

@interface Spriteuifont : CCSprite
+(Spriteuifont*)spriteuifontWithText:(NSString*)text font:(UIFont*)font color:(UIColor*)color;
@property (nonatomic, retain) NSString* string;
@end

Spriteuifont.m:

#import "Spriteuifont.h"

#import "UIView+additions.h"

@interface Spriteuifont ()
@property (nonatomic, retain) NSString* _string;
@property (nonatomic, retain) UIFont* _font;
@property (nonatomic, retain) UIColor* _color;
@end



@implementation Spriteuifont
@synthesize _string, _font, _color; // retain
-(void)dealloc {
    self._string = nil;
    self._font = nil;
    self._color = nil;
    [super dealloc];
}
+(Spriteuifont*)spriteuifontWithText:(NSString*)text font:(UIFont*)font color:(UIColor*)color {
    Spriteuifont* s = [[[self alloc] initWithText:text font:font color:color] autorelease];
    return s;
}
-(id)initWithText:(NSString*)text font:(UIFont*)font color:(UIColor*)color {
    self = [super init];
    if (self) {
        self._font = font;
        self._color = color;
        self.string = text;
    }
    return self;
}
-(void)refresh {
    const CGSize SIZE = [self._string sizeWithFont:self._font];
    UILabel* labelTestfont = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, SIZE.width, SIZE.height)] autorelease];
    labelTestfont.font = self._font;
    labelTestfont.backgroundColor = UIColor.clearColor;
    labelTestfont.opaque = NO;
    labelTestfont.text = self._string;
    labelTestfont.textColor = self._color;
    UIImage* img = [labelTestfont image];
    // GL_ONE or GL_ONE_MINUS_SRC_ALPHA ?
    CCTexture2D* aa = [[[CCTexture2D alloc] initWithCGImage:img.CGImage resolutionType:GL_ONE] autorelease];
    [self setTexture:aa];
    [self setTextureRect:labelTestfont.frame];
}
-(void)setString:(NSString *)string {
    self._string = string;
    [self refresh];
}
-(NSString*)string {
    return self._string;
}
@end

用法:

Spriteuifont* label = [Spriteuifont spriteuifontWithText:@"0" font:[UIFont fontWithName:@"myfontwhatever" size:16] color:UIColor.blackColor];

通过UIView类别.m文件包含:

#import <QuartzCore/QuartzCore.h>
@implementation UIView (additions)
-(UIImage*)image {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
@end

1 个答案:

答案 0 :(得分:0)

目前在Cocos2d-iphone中不支持OTF字体。我现在只使用本机iOS支持,通​​过CCTexture2D呈现内容,如问题中所述。也许对性能不好,但就我而言,它并不重要。