将多个UI图像和UI标签组合成1个图像

时间:2014-07-23 22:38:52

标签: ios objective-c uiimage uilabel cgrectmake

基本上我有一个主UIImage,它充当背景/边框。在UIImage内,我还有2个UIImages,在它们周围有一个间隙垂直分割,因此您仍然可以看到主背景UIImage的边框。在每一边我都有UILabel来描述图像。下面是我的意思,以帮助进入上下文。

enter image description here

我想要实现的是将其制作成1张图像,但保持所有当前位置,布局,图像布局(Aspect Fill)和标签尺寸以及标签背景颜色相同。我也希望这个图像质量一致,所以看起来还不错。

我已经查看了许多其他stackoverflow问题,到目前为止已经提出了以下问题,但它存在以下问题:

  • 不会将图片labels放置到正确的位置和尺寸
  • 没有标签或主图像的背景颜色
  • 没有将图像作为Aspect Fill(如UIImageViews),因此每张图片的外部也会被显示,并且没有被正确裁剪,如上例所示。

以下是我的代码到目前为止,有人可以帮助我实现它,如上图所示吗?我对iOS开发还很陌生,并且有点挣扎:

-(UIImage *)renderImagesForSharing{

    CGSize newImageSize = CGSizeMake(640, 640);
    NSLog(@"CGSize %@",NSStringFromCGSize(newImageSize));

    UIGraphicsBeginImageContextWithOptions(newImageSize, NO, 0.0);

    [self.mainImage.layer renderInContext:UIGraphicsGetCurrentContext()];
    [self.beforeImageSide.image drawInRect:CGRectMake(0,0,(newImageSize.width/2),newImageSize.height)];
    [self.afterImageSize.image drawInRect:CGRectMake(320,0,(newImageSize.width/2),newImageSize.height) blendMode:kCGBlendModeNormal alpha:1.0];

    [self.beforeLabel drawTextInRect:CGRectMake(60.0f, 0.0f, 200.0f, 50.0f)];
    [self.afterLabel drawTextInRect:CGRectMake(0.0f, 0.0f, 100.0f, 50.0f)];


    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

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

    UIGraphicsEndImageContext();
    return imagePNG;
}

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

我不明白为什么要使用drawInRect:来完成此任务。 由于您拥有图像和所有内容,因此您可以轻松创建图像中显示的视图。然后截取它的截图:

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*theImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData*theImageData=UIImageJPEGRepresentation(theImage, 1.0 ); //you can use PNG too
[theImageData writeToFile:@"example.jpeg" atomically:YES];

self.view更改为刚创建的视图

答案 1 :(得分:0)

它会给出一些想法。

UIGraphicsBeginImageContextWithOptions(DiagnosisView.bounds.size, DiagnosisView.opaque, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor redColor] set];
CGContextFillRect(ctx, DiagnosisView.frame);
[DiagnosisView.layer renderInContext:ctx];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSString *imagePath = [KdiagnosisFolderPath stringByAppendingPathComponent:FileName];
NSData *pngData = UIImagePNGRepresentation(img);
[pngData writeToFile:imagePath atomically:YES];
pngData = nil,imagePath = nil;