2014-01-31 57 views
0

我想合併iOS中的多個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]; 

但我不能得到任何圖像。我該如何解決它? 謝謝。

+0

'的UIImage * imageLeft = [UIImage的imageNamed:@ 「ICO-left.png」];'或'的UIImage * imageLeft = [UIImage的imageNamed:@ 「ICO-left.jpg」];' – vikingosegundo

+0

做什麼你的意思是'不能得到任何圖像'?調試時會發生什麼? – Wain

回答

0

我認爲你是不添加圖片(.png)的擴展,使這些

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

如果擴展名是.png,則不需要添加它。如果它是.jpg或.jpeg,則必須添加擴展名。 –

+0

這不是一個好的答案,您不應該將.png添加到您的圖像名稱中,並且特別是如果您要使用圖像沒有擴展名的xcassets圖像目錄。 – Climbatize

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

    }