簡體   English   中英

在iOS上合並多個UIImage

[英]merge multiple UIImages on iOS

我想在iOS中合並多個UIImage。 為此,我嘗試執行以下操作:

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

但是我無法得到任何圖像。 我該如何解決? 謝謝。

我認為您沒有添加圖片擴展名(.png),因此可以通過以下方式更改上面的兩行

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

我不確定這是否是您的問題,但是您可以嘗試一下。 有時候對我有用

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

這是我用來合並圖像的代碼。 (我認為我有時會在網上找到全部或部分內容)。 將其放在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