gpt4 book ai didi

cocoa - 如何绘制模糊的形状?

转载 作者:行者123 更新时间:2023-12-03 16:10:52 24 4
gpt4 key购买 nike

如何在 Cocoa 中绘制模糊形状?想象一个带有 blurRadius 的阴影,伴随着填充的路径,但没有锋利的前景路径形状。

我尝试的是使用带有阴影的填充路径,并将填充颜色设置为透明(alpha 0.0)。但这也使得阴影不可见,因为它显然考虑了阴影转换“对象”的 Alpha。

最佳答案

这实际上相当棘手。我为此苦苦挣扎了一段时间,直到我在 NSShadow 上想到了这个类别:

@implementation NSShadow (Extras)

//draw a shadow using a bezier path but do not draw the bezier path
- (void)drawUsingBezierPath:(NSBezierPath*) path alpha:(CGFloat) alpha
{
[NSGraphicsContext saveGraphicsState];
//get the bounds of the path
NSRect bounds = [path bounds];

//create a rectangle that outsets the size of the path bounds by the blur radius amount
CGFloat blurRadius = [self shadowBlurRadius];
NSRect shadowBounds = NSInsetRect(bounds, -blurRadius, -blurRadius);

//create an image to hold the shadow
NSImage* shadowImage = [[NSImage alloc] initWithSize:shadowBounds.size];

//make a copy of the shadow and set its offset so that when the path is drawn, the shadow is drawn in the middle of the image
NSShadow* aShadow = [self copy];
[aShadow setShadowOffset:NSMakeSize(0, -NSHeight(shadowBounds))];

//lock focus on the image
[shadowImage lockFocus];

//we want to draw the path directly above the shadow image and offset the shadow so it is drawn in the image rect
//to do this we must translate the drawing into the correct location
NSAffineTransform* transform=[NSAffineTransform transform];
//first get it to the zero point
[transform translateXBy:-shadowBounds.origin.x yBy:-shadowBounds.origin.y];

//now translate it by the height of the image so that it draws outside the image bounds
[transform translateXBy:0.0 yBy:NSHeight(shadowBounds)];
NSBezierPath* translatedPath = [transform transformBezierPath:path];

//apply the shadow
[aShadow set];

//fill the path with an arbitrary black color
[[NSColor blackColor] set];
[translatedPath fill];
[aShadow release];
[shadowImage unlockFocus];

//draw the image at the correct location relative to the original path
NSPoint imageOrigin = bounds.origin;
imageOrigin.x = (imageOrigin.x - blurRadius) + [self shadowOffset].width;
imageOrigin.y = (imageOrigin.y - blurRadius) - [self shadowOffset].height;

[shadowImage drawAtPoint:imageOrigin fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:alpha];
[shadowImage release];
[NSGraphicsContext restoreGraphicsState];
}

@end

关于cocoa - 如何绘制模糊的形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6232134/

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