2012-01-02 3 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

당신의 재연에 감사하지만 내 문제는 다른 것입니다. 나는 사다리꼴과 같은 4 가지 포인트를 가지고 있습니다. 사용자는 또한이 포인트를 변경하고 자신의 스타일을 만들 수 있습니다. 이제는 사용자가 만든 동일한 모양의 이미지를 자르고 싶습니다. 드레싱 포인트 –

+0

4 점을 마스크로 렌더링 한 다음 위의 코드를 사용할 수 있습니까? –

+0

죄송합니다. IOS 개발에 새로운입니다. 귀하의 의견을 이해할 수 없습니다. 예를 들어 4 포인트 CGPoint firstPoint, secondPoint, thirdPoint 및 사다리꼴의 fourthPoint가 있는데 위 코드를 사용하는 방법 감사합니다 –

관련 문제