ios – 如何基于不规则形状裁剪图像?

我想基于不规则形状的蒙版在iOS中裁剪图像.我怎样才能做到这一点?

解决方法

我不确定你想裁剪,但你想掩盖图像.这很容易做到,但你最终会发现它适用于某些图像,而不适用于其他图像.这是因为您需要在图像中使用正确的Alpha通道.

这里是我使用的代码,我从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,colorSpace,kCGImageAlphaPremultipliedFirst);

if (offscreenContext != NULL) {
    CGContextDrawImage(offscreenContext,CGRectMake(0,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"]];

在这种情况下,我使用圆形蒙版来制作圆形图像.你需要制作适合你需要的不规则面膜.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...