gpt4 book ai didi

objective-c - CoreGraphics Quartz 在透明 alpha 路径上绘制阴影

转载 作者:太空狗 更新时间:2023-10-30 03:15:33 24 4
gpt4 key购买 nike

在网上搜索了大约 4 个小时没有得到答案,所以:
如何在具有透明度的路径上绘制阴影?

- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(c, 2);
CGContextSetStrokeColorWithColor(c, [[UIColor whiteColor] CGColor]);
CGContextSetShadowWithColor(c, CGSizeMake(0, 5), 5.0, [[UIColor blackColor]CGColor]);
CGContextSetFillColorWithColor(c, [[UIColor colorWithWhite:1.0 alpha:0.8] CGColor]);

// Sample Path
CGContextMoveToPoint(c, 20.0, 10.0);
CGContextAddLineToPoint(c, 100.0, 40.0);
CGContextAddLineToPoint(c, 40.0, 70.0);
CGContextClosePath(c);

CGContextDrawPath(c, kCGPathFillStroke);
}

我注意到的第一件事是,阴影仅围绕笔划。但这不是目前的问题。路径/矩形后面的阴影仍然可见,这意味着:阴影颜色正在影响我的路径的填充颜色。填充颜​​色应该是白色而不是灰色。如何解决这个问题?

最佳答案

您将不得不裁剪上下文并绘制两次。

首先,您创建一个对您的路径的引用,因为您将不得不使用它几次并保存您的图形上下文,以便您可以返回它。

然后将图形上下文剪切到路径之外的唯一绘图。这是通过将您的路径添加到覆盖整个 View 的路径来完成的。剪裁后,用阴影绘制路径,使其绘制在外面。

接下来,将图形上下文恢复到裁剪之前的状态,并在没有阴影的情况下再次绘制路径。

它在橙色背景上看起来像这样(白色背景不是很明显)

The described drawing on a orange background

完成上述绘图的代码是这样的:

- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(c, 2);
CGContextSetStrokeColorWithColor(c, [[UIColor whiteColor] CGColor]);
CGContextSetFillColorWithColor(c, [[UIColor colorWithWhite:1.0 alpha:0.5] CGColor]);

// Sample Path
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 20.0, 10.0);
CGPathAddLineToPoint(path, NULL, 40.0, 70.0);
CGPathAddLineToPoint(path, NULL, 100.0, 40.0);
CGPathCloseSubpath(path);

// Save the state so we can undo the shadow and clipping later
CGContextSaveGState(c);
{ // Only for readability (so we know what are inside the save/restore scope
CGContextSetShadowWithColor(c, CGSizeMake(0, 5), 5.0, [[UIColor blackColor]CGColor]);
CGFloat width = CGRectGetWidth(self.frame);
CGFloat height = CGRectGetHeight(self.frame);

// Create a mask that covers the entire frame
CGContextMoveToPoint(c, 0, 0);
CGContextAddLineToPoint(c, width, 0);
CGContextAddLineToPoint(c, width, height);
CGContextAddLineToPoint(c, 0, height);
CGContextClosePath(c);

// Add the path (which by even-odd rule will remove it)
CGContextAddPath(c, path);

// Clip to that path (drawing will only happen outside our path)
CGContextClip(c);

// Now draw the path in the clipped context
CGContextAddPath(c, path);
CGContextDrawPath(c, kCGPathFillStroke);
}
CGContextRestoreGState(c); // Go back to before the clipping and before the shadow

// Draw the path without the shadow to get the transparent fill
CGContextAddPath(c, path);
CGContextDrawPath(c, kCGPathFillStroke);
}

如果你想让整个阴影一样浓,又不想填充颜色的透明度让阴影变弱那么你可以在第一次填充的时候使用完全不透明的颜色。它会被剪掉,所以无论如何它都不会在路径中可见。它只会影响阴影。

关于objective-c - CoreGraphics Quartz 在透明 alpha 路径上绘制阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6709064/

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