简体   繁体   English

在iOS上合并多个UIImage

[英]merge multiple UIImages on iOS

I want to merge multiple UIImages in iOS. 我想在iOS中合并多个UIImage。 To do this, I tried to do as below: 为此,我尝试执行以下操作:

UIImage *imageLeft = [UIImage imageNamed:@"ico-left"];
UIImage *imageRight = [UIImage imageNamed:@"ico-right"];
CGSize size = CGSizeMake(imageLeft.size.width + imageRight.size.width, imageLeft.size.height);
UIGraphicsBeginImageContext(size);
[imageLeft drawInRect:CGRectMake(0, 0, imageLeft.size.width, imageLeft.size.height)];
[imageRight drawInRect:CGRectMake(imageLeft.size.width, 0, imageRight.size.width, imageRight.size.height)];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, finalImage.size.width, finalImage.size.height)];
imageView.image = finalImage;
[cell.contentView addSubview:imageView];

But I cannot get any image. 但是我无法得到任何图像。 How can I fix it? 我该如何解决? Thanks. 谢谢。

I think you are not adding extension of image (.png) so change your upper two lines by these 我认为您没有添加图片扩展名(.png),因此可以通过以下方式更改上面的两行

    UIImage *imageLeft = [UIImage imageNamed:@"ico-left.png"];
    UIImage *imageRight = [UIImage imageNamed:@"ico-right.png"];

I am not sure whether this is your problem but you can give it a try. 我不确定这是否是您的问题,但是您可以尝试一下。 Sometimes it worked for me 有时候对我有用

NSString *path1 = [[NSBundle mainBundle] pathForResource:@"ico-left" ofType:@"png"];
NSString *path2 = [[NSBundle mainBundle] pathForResource:@"ico-right" ofType:@"png"];
UIImage *imageLeft = [[UIImage alloc] initWithContentsOfFile:path1];
UIImage *imageRight = [[UIImage alloc] initWithContentsOfFile:path2];

Here's the code I use to merge images. 这是我用来合并图像的代码。 (I think I found all or part of it online at some point). (我认为我有时会在网上找到全部或部分内容)。 Put it in a UIImage category. 将其放在UIImage类别中。

    // NOTE! this method should only be called from the main thread because of
    // UIGraphicsGetImageFromCurrentImageContext();
    - (UIImage *)merge:(UIImage *)image atRect:(CGRect)pos overlay:(BOOL)overlay fillColor:(UIColor *)fill 
    {
        UIGraphicsBeginImageContext(self.size);

        UIImage *bottom = (overlay)?self:image;
        UIImage *top = (overlay)?image:self;

        CGRect lf = CGRectMake(0, 0, self.size.width, self.size.height);

        CGRect bottomRect = (overlay)?lf:pos;
        CGRect topRect = (overlay)?pos:lf;

        if (fill){
            [fill setFill];
            CGContextFillRect (UIGraphicsGetCurrentContext(), topRect);
        }

        [bottom drawInRect:bottomRect];
        [top drawInRect:topRect];

        UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();    
        UIGraphicsEndImageContext();
        return destImage;   

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM