在iOS上合并多个UIImages

时间:2014-01-31 12:57:36

标签: ios uiimageview uiimage

我想在iOS中合并多个UIImages。 为此,我尝试按以下方式执行:

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];

但我无法得到任何形象。我该如何解决? 感谢。

3 个答案:

答案 0 :(得分:0)

我认为你没有添加图像扩展名(.png)所以用这些

来改变你的上面两行
    UIImage *imageLeft = [UIImage imageNamed:@"ico-left.png"];
    UIImage *imageRight = [UIImage imageNamed:@"ico-right.png"];

答案 1 :(得分:0)

我不确定这是否是您的问题,但您可以尝试一下。有时它对我有用

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];

答案 2 :(得分:0)

这是我用来合并图像的代码。 (我想我在某个时候在线发现了全部或部分内容)。把它放在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;   

    }