我想制作类似于某些贺卡应用程序的iphone应用程序,在那里我可以在一些预先准备好的背景图像(卡片)上写文字。
感谢。
答案 0 :(得分:10)
这是一种将字符串刻录到图像中的方法。您可以根据自己的喜好调整字体大小和其他参数进行配置。
/* Creates an image with a home-grown graphics context, burns the supplied string into it. */
- (UIImage *)burnTextIntoImage:(NSString *)text :(UIImage *)img {
UIGraphicsBeginImageContext(img.size);
CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height);
[img drawInRect:aRectangle];
[[UIColor redColor] set]; // set text color
NSInteger fontSize = 14;
if ( [text length] > 200 ) {
fontSize = 10;
}
UIFont *font = [UIFont boldSystemFontOfSize: fontSize]; // set text font
[ text drawInRect : aRectangle // render the text
withFont : font
lineBreakMode : UILineBreakModeTailTruncation // clip overflow from end of last line
alignment : UITextAlignmentCenter ];
UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext(); // extract the image
UIGraphicsEndImageContext(); // clean up the context.
return theImage;
}
答案 1 :(得分:5)
谢谢Rayfleck!它奏效了。
添加视网膜显示器的可选兼容性(修复'@ 2x'版本图像放大期间的乱码字母):
取代:
UIGraphicsBeginImageContext(img.size);
有条件的:
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions(img.size,NO,0.0);
else
UIGraphicsBeginImageContext(img.size);
答案 2 :(得分:0)
更新ios7 ...
/* Creates an image with a home-grown graphics context, burns the supplied string into it. */
- (UIImage *)burnTextIntoImage:(NSString *)text :(UIImage *)img {
UIGraphicsBeginImageContext(img.size);
CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height);
[img drawInRect:aRectangle];
[[UIColor redColor] set]; // set text color
NSInteger fontSize = 14;
if ( [text length] > 200 ) {
fontSize = 10;
}
UIFont *font = [UIFont fontWithName:@"Courier" size:fontSize];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
paragraphStyle.alignment = NSTextAlignmentRight;
NSDictionary *attributes = @{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: [UIColor whiteColor]};
[text drawInRect:aRectangle withAttributes:attributes];
UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext(); // extract the image
UIGraphicsEndImageContext(); // clean up the context.
return theImage;
}
答案 3 :(得分:0)
这种方法考虑了屏幕的比例,并且它非常直观
UIImage * img = ...
UIImageView * iV = [[UIImageView alloc] initWithImage:img];
UILabel * l = [[UILabel alloc] initWithFrame:iV.bounds];
l.textAlignment = ...;
l.adjustsFontSizeToFitWidth = YES;
l.textColor = ...;
l.font = ...;
l.text = ...;
[iV addSubview:l];
UIGraphicsBeginImageContextWithOptions(iV.bounds.size, NO, 0);
[iV.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return finalImage