2011-12-13 105 views
4

我想掩蓋兩個圖像圖片遮罩+ iPhone SDK

圖片1:

enter image description here

圖片2:

enter image description here

現在我想合併這兩個圖像像image2將會出現在image1的中心。

我讀過Any idea why this image masking code does not work?"How to Mask an Image"

但在使用此功能: - 使用此功能我得到的輸出

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage { 
    CGImageRef maskRef = maskImage.CGImage;  
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef), 
             CGImageGetHeight(maskRef), 
             CGImageGetBitsPerComponent(maskRef), 
             CGImageGetBitsPerPixel(maskRef), 
             CGImageGetBytesPerRow(maskRef), 
             CGImageGetDataProvider(maskRef), NULL, false); 

    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask); 
    return [UIImage imageWithCGImage:masked]; 
} 

但是,就是: -

enter image description here

+3

參考http://stackoverflow.com/questions/996292/how-to-mask-a-square-image-into-an-image-with-round-corners-in-the-iphone-sdk – Maulik

+0

好問題@shweta,保持它:) – SagarPPanchal

回答

1

據我所知,問題不在maskImage:withMask:。您發佈的錯誤輸出並不是錯誤的:image1的像素爲黑色,image2不可見。

問題可能出現在您用來加載imagemask的函數中或在生成圖形輸出的代碼中。 其實在我看來,你得到了正確的輸出,但使用了錯誤的顏色空間(不帶alpha的灰度)。檢查您提供的參數image是否實際上採用RGBa格式,並且返回的UIImage未使用DeviceGray作爲顏色空間繪製到其他一些CGContext上。

我想到的另一個可能的原因是您倒置了image1和image2。根據文檔,mask應擴大到image(見下文)的大小,但你有一個小圖像。這似乎也是合理的,因爲image1是灰度的,儘管當我試圖交換image1和image2時,我沒有修改image1作爲輸出。


要運行我用連接的圖像中的測試,然後複製&粘貼方法-(UIImage *)maskImage:(UIImage *)image withMask:(UIImage *)maskImage原樣。

我用一個視圖一個簡單的iOS項目和一個UIImageView內側(與標籤1),並且在控制器以下代碼:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    UIImageView *imageView=(UIImageView *)[self.view viewWithTag:1]; 

    UIImage *im1=[UIImage imageNamed:@"image1"]; 
    UIImage *im2=[UIImage imageNamed:@"image2"]; 

    imageView.image=[self maskImage:im2 withMask:im1]; 

} 

我得到以下輸出(它是右):

image2 using image1 as mask

如果你誤用反轉IM2 IM1,你不是image1的修改。