0

我想用 Quartz 做一些这样的效果:

在此处输入图像描述

我想在imageView上面加一层,但是有些区域没有覆盖,我该如何实现呢?有任何想法吗?谢谢。

4

1 回答 1

1

不清楚你是在谈论 iOS 还是 MacOS,但原则是一样的。我能想到的最简单的方法是用半透明的灰色填充覆盖视图,然后用偏移阴影打孔......这是一个简单的例子:

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);

    // Replace with your location, spot radius, and blur radius
    CGPoint spotLoc = CGPointMake(200,200);
    CGFloat spotRadius = 100;
    CGFloat blurRadius = 5;

    // Draw 50% black overlay over the entire view
    CGContextSetFillColorWithColor(ctx, [[UIColor colorWithRed: 0 green:0 blue:0 alpha:0.5] CGColor]);
    CGContextFillRect(ctx, CGContextGetClipBoundingBox(ctx));

    // Then punch out spot using an offset shadow
    CGRect spotRect = CGRectMake(spotLoc.x - spotRadius, spotLoc.y - spotRadius, 2 * spotRadius, 2 * spotRadius);
    CGFloat xOffset = CGRectGetMaxX(spotRect) - CGRectGetMinX(self.bounds);
    CGContextSetBlendMode(ctx, kCGBlendModeDestinationOut);
    CGContextSetFillColorWithColor(ctx, [[UIColor blackColor] CGColor]);
    CGContextSetShadowWithColor(ctx, CGSizeMake(xOffset, 0), blurRadius, [[UIColor blackColor] CGColor]);
    CGContextTranslateCTM(ctx, -xOffset, 0);
    CGContextFillEllipseInRect(ctx, spotRect);

    CGContextRestoreGState(ctx);
}

如果你想要硬边,甚至不用担心偏移和阴影,只需CGContextFillEllipseInRect在将混合模式设置为 . 后使用不透明填充即可kCGBlendModeDestinationOut

编辑:在我看来,您也可以使用径向渐变效果做类似的事情,但是以您给出的效果为例,我猜边缘更模糊,而不是均匀的渐变,但很难说. 无论如何,Quartz 通过它的阴影机制免费为您提供模糊效果,所以为什么不使用它,对吧?

于 2013-07-17T13:43:57.337 回答