如何将UIImage和UILabel组合成一个图像并保存

Des*_*ond 10 iphone xcode uiimageview uiimage ios

我有2个UILabel和2个图像,我需要合并到一个UIImage中进行保存.

我知道我可以用屏幕截图来做,但是我的主要图像是圆形的,所以如果我将其缩小,它仍然会显示出锐利的边缘.

我可以这样做来组合图像:

//CGSize newImageSize = CGSizeMake(cropImage.frame.size.width, cropImage.frame.size.height);
CGSize newImageSize = CGSizeMake(480, 320);
NSLog(@"CGSize %@",NSStringFromCGSize(newImageSize));

UIGraphicsBeginImageContextWithOptions(newImageSize, NO, 0.0); //retina res
[self.viewForImg.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

NSData *imgData =  UIImageJPEGRepresentation(image, 0.9); //UIImagePNGRepresentation ( image ); // get JPEG representation
UIImage * imagePNG = [UIImage imageWithData:imgData]; // wrap UIImage around PNG representation

UIGraphicsEndImageContext();
return imagePNG;
Run Code Online (Sandbox Code Playgroud)

但不知道如何添加UILabel.

任何回复都非常感谢.

iDe*_*Dev 17

用于[myLabel.layer renderInContext:UIGraphicsGetCurrentContext()];在当前上下文中绘制.

例如: -

    UIGraphicsBeginImageContextWithOptions(newImageSize, NO, 0.0); //retina res
    [self.viewForImg.layer renderInContext:UIGraphicsGetCurrentContext()];
    [myLabel.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
Run Code Online (Sandbox Code Playgroud)

根据您的评论,如果您想在特定框架中绘制它,请执行以下操作,

[myLabel drawTextInRect:CGRectMake(0.0f, 0.0f, 100.0f, 50.0f)];
Run Code Online (Sandbox Code Playgroud)

如果你想为背景上色,试试这个,

CGRect drawRect = CGRectMake(rect.origin.x, rect.origin.y,rect.size.width, rect.size.height); 
CGContextSetRGBFillColor(context, 100.0f/255.0f, 100.0f/255.0f, 100.0f/255.0f, 1.0f); 
CGContextFillRect(context, drawRect);
Run Code Online (Sandbox Code Playgroud)

或者你可以检查这个问题设置一个CGContext透明背景.