我正在尝试编写一个将文本字段文本转换为图像的函数(示例)。我试图搜索一个示例,大多数示例也覆盖了图像上的文本。有可能给我一些例子或提示如何做吗?
几种方法是可能的。
如果您有现有的图像UITextField
,UITextView
或者UILabel
只想将其渲染为图像,则可以采用传统的快照方法,例如:
- (UIImage *)imageForView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES]; // if we have efficient iOS 7 method, use it ...
else
[view.layer renderInContext:UIGraphicsGetCurrentContext()]; // ... otherwise, fall back to tried and true methods
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
如果要使用通用的“从文本创建图像”例程,则在iOS 7中,它看起来像:
- (UIImage *)imageFromString:(NSString *)string attributes:(NSDictionary *)attributes size:(CGSize)size
{
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
[string drawInRect:CGRectMake(0, 0, size.width, size.height) withAttributes:attributes];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
上面将创建一个图像,其大小将根据文本而有所不同。显然,如果只需要固定大小的图像,则可以使用constants frame
,而不是动态构建它。
无论如何,您可以这样使用上面的代码:
NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:20],
NSForegroundColorAttributeName : [UIColor blueColor],
NSBackgroundColorAttributeName : [UIColor clearColor]};
UIImage *image = [self imageFromString:string attributes:attributes size:self.imageView.bounds.size];
如果您需要支持早期的iOS版本,则可以使用以下技术:
- (UIImage *)imageFromString:(NSString *)string font:(UIFont *)font size:(CGSize)size
{
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
[string drawInRect:CGRectMake(0, 0, size.width, size.height) withFont:font lineBreakMode: NSLineBreakByWordWrapping];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
这些中的每一个都有很多很多的排列。这仅取决于您要实现的目标。
另一种方法是简单地同时拥有UIImageView
和UILabel
/UITextView
视图对象,如果有从服务器的图像,设置的图像UIImageView
和文本,设置text
了的UILabel
/ UITextView
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句