将两个图像合并为单个图像,然后顶部图像在ios sdk中变大

时间:2014-11-01 11:58:43

标签: ios iphone uiimage xcode6 uigraphicscontext

我有两个包含两个不同图像的imageView。我的firstImageview有主要图片,然后我添加了一个图像视图作为firstImageview的子视图,如[firstImageview addSubView:secondImageview]。我需要将它放在一张图片中。

我正在使用以下代码(它运作顺畅):

- (UIImage*)imageByCombiningImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {
    UIImage *image = nil;

    CGSize newImageSize = CGSizeMake(MAX(firstImage.size.width, secondImage.size.width), MAX(firstImage.size.height, secondImage.size.height));
    if (UIGraphicsBeginImageContextWithOptions != NULL) {
        UIGraphicsBeginImageContextWithOptions(newImageSize, NO, [[UIScreen mainScreen] scale]);
    } else {
       // UIGraphicsBeginImageContext(newImageSize);
    }
    [firstImage drawAtPoint:CGPointMake(roundf((newImageSize.width-firstImage.size.width)/2),
                                        roundf((newImageSize.height-firstImage.size.height)/2))];
    [secondImage drawAtPoint:CGPointMake(roundf((newImageSize.width-secondImage.size.width)/2),
                                         roundf((newImageSize.height-secondImage.size.height)/2))];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

但是在我的generatedImage中,topImage secondImageview.image变大了。

我的观点看起来像(在合并之前):

image prior to merge

合并后生成的图像(顶部图像变大):

image after merge

如果secondImageview不变大,我如何合并这些图像?

1 个答案:

答案 0 :(得分:0)

我通过以下代码解决了我的问题

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