我有一个NSString对象。 我想将它写入现有的UIImage对象。 UIImage对象已经有一些与之关联的图像。 我想将字符串写入相同的图像。 我如何实现它?
答案 0 :(得分:2)
编辑: 以下是编辑UIImage并在其上书写文本的基本步骤。
在图像视图上显示文本和标签并显示更容易。 答案已经存在。
然后将其更新为文件或在屏幕上显示....
答案 1 :(得分:1)
NSString
无法成为UIImage
。然而,听起来你想做的就是在图像上面插入一些文字,这很容易实现。
创建UILabel *label
。使用label.text = myString;
将文本设置为字符串。
创建UIImageView *imageView
。使用imageView.image = myimage
将视图图像设置为图像。
将UILabel
作为UIImageView
的子视图(作为UIView
的子类,它需要子视图)添加[imageView addSubview:label];
(或删除标签)如果您正在使用IB,则为imageview。
确保将标签背景设置为[UIColor clearColor]
或设置alpha = 0.0
以使其透明。
答案 2 :(得分:1)
您可以将图像和字符串绘制(合成)到图形上下文中,然后抓取生成的UIImage。
要使用renderInContext
绘制图像。
要绘制文本,请使用CGContextShowTextAtPoint
。
获得结果图像
UIImage *compositeImage = UIGraphicsGetImageFromCurrentImageContext();
答案 3 :(得分:0)
这是我的代码。我有一个35x480视图,我在其上绘制旋转90度的文本。我希望这有帮助。我绘制图像,然后绘制文本,以便显示出来。它看起来像一个窗口的窗口标题。
我绘制图像,然后绘制drawRect上的文本。
@synthesize topView;
@synthesize delegate;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
topView.backgroundColor = [UIColor clearColor];
topView.opaque = NO;
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
UIGraphicsBeginImageContext(img.image.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
// draw titleborder
CGRect titleRect = CGRectMake(0, 0, 35, 480);
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"titleborder" ofType:@"png"];
UIImage *titleImage = [[UIImage alloc] initWithContentsOfFile:filePath];
[titleImage drawInRect:titleRect];
[self bringSubviewToFront:topView];
UIFont *font = [UIFont boldSystemFontOfSize:16.0];
CGRect textRect = CGRectMake(0, rect.size.height/2, 480, 40);
NSLog(@"text rect frame: %@", NSStringFromCGRect(textRect));
[self drawText:[[NSString alloc] initWithFormat:@"My Window Title"] rect:textRect context:context font:font red:1.0 green:1.0 blue:1.0 alpha:1.0] ;
CGContextRestoreGState(context);
}
- (void) drawText: (NSString *)text rect: (CGRect)rect context:(CGContextRef)context font:(UIFont *)font red:(CGFloat)r green: (CGFloat)g blue:(CGFloat)b alpha:(CGFloat)alpha {
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetRGBFillColor(context, r, g, b, alpha); // 6
CGContextSetRGBStrokeColor(context, 1, 1, 1, 1);
CGAffineTransform transform1 = CGAffineTransformMakeRotation(-90.0 * M_PI/180.0);
CGContextConcatCTM(context, transform1);
CGSize sizeOfString = [text sizeWithFont:font];
CGContextTranslateCTM(context, (sizeOfString.width/2) - 420,-232);
[text drawInRect:rect withFont:font lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentLeft];
}