iPhone如何在圆圈内剪辑圆圈?

时间:2011-12-13 11:29:51

标签: iphone drawing quartz-graphics geometry clip

我有两个圆圈,一个更大,一个更小。我想从较大的圆圈中剪切较小的圆圈,然后使用新的形状(带有孔的大圆圈)将其应用于任意图像。我用石英玩过一点,但找不到解决方法。有没有简单的方法呢?

1 个答案:

答案 0 :(得分:1)

这是我从stackoverflow获得的一些代码。您可以调用一次以使用孔掩模创建图像,然后再次调用它以使用该图像来屏蔽源图像。

- (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;
}