2012-01-02 20 views

答えて

3

私はあなたが切り抜きたいとは思っていませんが、代わりに画像をマスクしたいと思います。これはかなり簡単ですが、最終的に一部の画像だけではなく、他の画像では機能することがわかります。これは、画像に適切なアルファチャンネルが必要なためです。

ここで私が使用するコードは、私はstackoverflowから得た。 (Problem with transparency when converting UIView to UIImage

CGImageRef CopyImageAndAddAlphaChannel(CGImageRef sourceImage) { 
CGImageRef retVal = NULL; 

size_t width = CGImageGetWidth(sourceImage); 
size_t height = CGImageGetHeight(sourceImage); 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

CGContextRef offscreenContext = CGBitmapContextCreate(NULL, width, height, 
                 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst); 

if (offscreenContext != NULL) { 
    CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), sourceImage); 

    retVal = CGBitmapContextCreateImage(offscreenContext); 
    CGContextRelease(offscreenContext); 
} 

CGColorSpaceRelease(colorSpace); 

return retVal; 
} 

- (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 sourceImage = [image CGImage]; 
CGImageRef imageWithAlpha = sourceImage; 
//add alpha channel for images that don't have one (ie GIF, JPEG, etc...) 
//this however has a computational cost 
// needed to comment out this check. Some images were reporting that they 
// had an alpha channel when they didn't! So we always create the channel. 
// It isn't expected that the wheelin application will be doing this a lot so 
// the computational cost isn't onerous. 
//if (CGImageGetAlphaInfo(sourceImage) == kCGImageAlphaNone) { 
imageWithAlpha = CopyImageAndAddAlphaChannel(sourceImage); 
//} 

CGImageRef masked = CGImageCreateWithMask(imageWithAlpha, mask); 
CGImageRelease(mask); 

//release imageWithAlpha if it was created by CopyImageAndAddAlphaChannel 
if (sourceImage != imageWithAlpha) { 
    CGImageRelease(imageWithAlpha); 
} 

UIImage* retImage = [UIImage imageWithCGImage:masked]; 
CGImageRelease(masked); 

return retImage; 
} 

そして、あなたはこのようにそれを呼び出します。この場合、

customImage = [customImage maskImage:customImage withMask:[UIImage imageNamed:@"CircularMask.png"]]; 

、私は円形画像を作るために、円形のマスクを使用しています。あなたのニーズに合った不規則なマスクを作る必要があります。

+0

あなたの再生のためにありがとうが、私の問題はelse.I台形のような4つの異なる点があります。ユーザーはまた、これらのポイントを変更し、独自のstyle.Nowは、ユーザーが作成している同じ形のような画像をトリミングするドレッシングポイント –

+0

4点を取ってマスクにレンダリングし、上記のコードを使用できますか? –

+0

申し訳ありませんIOS開発の新機能です。あなたのことを理解できません。例えば、4ポイントのCGPoint firstPoint、secondPoint、thirdPoint、四角形の四角形があり、上記のコードをどのように使うのですか?ありがとう –

関連する問題