gpt4 book ai didi

ios - CGContextClipToMask 不剪辑

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:41:59 24 4
gpt4 key购买 nike

此代码生成下图。据我了解 CGContextClipToMask,红色矩形不应该可见,因为它在裁剪区域之外。我在这里错过了什么?感谢您的帮助!

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
CGContextFillRect(context, rect);
CGContextSetLineWidth(context, 20);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);

// draw partial circle
UIBezierPath *arc = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:NO];
CGContextAddPath(context, [arc CGPath]);
CGContextStrokePath(context);

// create mask
CGImageRef mask = CGBitmapContextCreateImage(context);
self.maskCreated(mask);

// save state
CGContextSaveGState(context);

// clip with mask
CGContextClipToMask(context, rect, mask);

// draw test rect
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillRect(context, CGRectMake(0, 0, 100, 100));

// restore state
CGContextRestoreGState(context);

Code Result

最佳答案

documentation对于 CGContextClipToMask 说:

If mask is an image, then it must be in the DeviceGray color space, may not have an alpha component, and may not be masked by an image mask or masking color.

我假设您的代码位于 UIView 子类的 -drawRect: 方法中,因此您使用的是 CGContext这是提供给您的,它位于 RGB 颜色空间中,并且可能具有 alpha 分量。您的 mask 图像是根据该上下文创建的,因此它具有相同的属性。

要解决此问题,请使用单独的位图上下文生成 mask ,使用没有 alpha 的灰色色彩空间。这是一个独立的示例,它执行与您的代码类似的操作。

- (void)drawRect:(CGRect)rect
{
// Create a context for the mask
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef maskContext = CGBitmapContextCreate(NULL, rect.size.width, rect.size.height, 8, 0, colorSpace, kCGImageAlphaNone | kCGBitmapByteOrderDefault);
CGColorSpaceRelease(colorSpace);

// Fill with black
CGContextSetFillColorWithColor(maskContext, [UIColor blackColor].CGColor);
CGContextFillRect(maskContext, rect);

// Draw an arc in white
CGContextSetLineWidth(maskContext, 20);
CGContextSetStrokeColorWithColor(maskContext, [UIColor whiteColor].CGColor);
CGContextAddArc(maskContext, CGRectGetMidX(rect), CGRectGetMidY(rect), 50, M_PI, 0, false);
CGContextStrokePath(maskContext);

// Create the mask image from the context, and discard the context
CGImageRef mask = CGBitmapContextCreateImage(maskContext);
CGContextRelease(maskContext);

// Now draw into the view itself
CGContextRef context = UIGraphicsGetCurrentContext();

// Apply the mask
CGContextClipToMask(context, rect, mask);

// Then draw something that overlaps the mask
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillRect(context, rect);

// Make sure to clean up when we're done
CGImageRelease(mask);
}

关于ios - CGContextClipToMask 不剪辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17721959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com