gpt4 book ai didi

ios - DrawText on Image with text 调整到图像的大小

转载 作者:行者123 更新时间:2023-12-01 17:31:42 34 4
gpt4 key购买 nike

我正在图像上绘制文本。文本绘制没有任何问题,但我的文本是动态的,有时它的字符更多,有时它更少。

从下图中您可以看到“ 这是超过图像 的 320 宽度的长消息,因为图像 的 没有出现。

我希望所有消息都显示在下一行,因为我的消息是动态的,我想以 320 * 480 大小的图像显示它,这里我显示小图像只是为了测试目的。

这是绘制文本的代码:

-(UIImage *)addText:(UIImage *)img text:(NSString *)text1{

int w = img.size.width;
int h = img.size.height;
//lon = h - lon;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);

char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];

CGContextSelectFont (context, // 3
"Helvetica-Bold",
15,
kCGEncodingMacRoman);
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetRGBFillColor(context, 255, 255, 255, 1);
CGContextShowTextAtPoint(context, 4, 52, text, strlen(text));
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
}

enter image description here

最佳答案

试试这段代码:

lblText.text=[NSString stringWithFormat:@"Put Your Text"];
lblText.font = [UIFont fontWithName:@"Helvetica" size:10.0f];
CGPoint point=lblText.center;
imgview.image =[self drawText:lblText.text inImage:imgview.image atPoint:point];


//Save it in Document directory for Checking Purpose...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *image1 = imgview.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image1);
[imageData writeToFile:savedImagePath atomically:NO];


-(UIImage *) drawText:(NSString*) text inImage:(UIImage*)image atPoint:(CGPoint)point
{
UIFont *font =lblText.font;;
if ([UIScreen instancesRespondToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(imgview.frame.size, NO, 0.0f);
} else {
UIGraphicsBeginImageContext(imgview.frame.size);
}

[image drawInRect:CGRectMake(0,0,imgview.frame.size.width,imgview.frame.size.height)];
CGRect rect = CGRectMake(point.x,point.y,lblText.frame.size.width, lblText.frame.size.height);//Set Frame as per your Requirement
[lblText.textColor set];
[text drawInRect:CGRectIntegral(rect) withFont:font];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return newImage;
}

我会帮你的。

关于ios - DrawText on Image with text 调整到图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19585573/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com