gpt4 book ai didi

ios - 带有透明圆角矩形的 UIView?

转载 作者:行者123 更新时间:2023-11-29 02:19:15 27 4
gpt4 key购买 nike

首先,我寻找并发现了这个: Cut transparent hole in UIView在我的 View 上放置多个透明矩形,但现在我需要将这些矩形圆角化,如下所示: http://postimg.org/image/ozxr0m5sh/所以我混合了一些我发现的代码并这样做了,但由于某种原因它只适用于第一个矩形,这里是自定义 View 的完整代码:(如果取消方法“addRoundedRect...”调用,它适用于所有矩形)。

- (void)drawRect:(CGRect)rect{

[backgroundColor setFill];
UIRectFill(rect);

// clear the background in the given rectangles
for (NSValue *holeRectValue in rectsArray) {
CGRect holeRect = [holeRectValue CGRectValue];
CGRect holeRectIntersection = CGRectIntersection( holeRect, rect );
CGContextRef context = UIGraphicsGetCurrentContext();

if( CGRectIntersectsRect( holeRectIntersection, rect ) )
{
addRoundedRectToPath(context, holeRectIntersection, 6, 6);
CGContextClosePath(context);
CGContextClip(context);
CGContextClearRect(context, holeRectIntersection);
CGContextSetFillColorWithColor( context, [UIColor clearColor].CGColor );
CGContextFillRect( context, holeRectIntersection);
}

}

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight){
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM (context, ovalWidth, ovalHeight);
fw = CGRectGetWidth (rect) / ovalWidth;
fh = CGRectGetHeight (rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2);
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
CGContextClosePath(context);
CGContextRestoreGState(context);
}

最佳答案

在 iOS 中,通常最好不要使用 drawRect。它往往比其他呈现内容的方法慢。

关于为什么不能在 View 中打出多个圆边孔的问题,我不知 Prop 体答案,但我建议采用不同的方法。而不是在 drawRect 方法中使用 CGContexts。

使用您需要的任何内容设置您的 View 。然后创建一个与 View 大小相同的 CAShapeLayer 并用路径填充它(形状层需要 CGPath,但您可以创建一个 UIBezierPath 并从中获取 CGPath。)将形状层附加为 View 层的蒙版。 (不过,您放入 mask 层的形状定义了 View 的不透明部分,因此您必须创建一个填充 mask 的形状,然后用其他形状在其中打洞。

关于ios - 带有透明圆角矩形的 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28377906/

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