如何使用iPhone上的CoreGraphics在ImageView上绘制文本
可以在UIImageView上方使用UILabel,或者在当前的图形上下文中绘制字符串
- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode
TextImageView.h
@interface TextImageView : UIView
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSString *text;
@end
TextImageView.m
@implementation TextImageView
- (void)drawRect:(CGRect)rect
{
[self.image drawInRect:self.bounds];
[self.text drawInRect:self.bounds
withAttributes:@{}];
}
@end
被接受的答案中的方法已经过时了。您应该使用的方法是- [NSString drawInRect:withAttributes:]
。
您应该在UIView
子类的drawRect:
方法中调用此方法,但如果您子类化UIImageView
,drawRect:
将永远不会被调用。(从文档中得知:“UIImageView不会调用其子类的drawRect:方法。”)
因此,您真的无法在UIImageView
上绘制文本,但是您可以子类化UIView
并像上面提出的那样绘制带有文本的图像。
[@"test" drawInRect: CGRectMake(0, 0, 10, 10) withFont:[UIFont systemFontOfSize:8]];
该方法可将字符串绘制到指定的矩形区域内,并使用指定大小的字体进行绘制。 - Marty