gpt4 book ai didi

ios - 带圆角的 UIView : how to clip subviews correctly?

转载 作者:IT王子 更新时间:2023-10-29 08:12:02 27 4
gpt4 key购买 nike

我创建了一个 UIView 的子类,它覆盖了 drawRect: 并使用 AddArcToPoint() 来绘制圆角。 (我不想使用图层的圆角半径属性,因为我需要定义哪些角必须圆角。)然而,我无法克服的问题是:如果我在 (0|0) 处添加一个 subview ,它会隐藏我的圆角。知道我该如何解决这个问题吗?我希望它能很好地剪裁。

下面是绘制圆角矩形的代码。它是 Monotouch,但任何开发人员都应该可以阅读。

(您可以在此处找到完整代码:https://github.com/Krumelur/RoundedRectView)

public override void Draw (RectangleF rect)
{
using (var oContext = UIGraphics.GetCurrentContext())
{
oContext.SetLineWidth (this.StrokeWidth);
oContext.SetStrokeColor (this.oStrokeColor.CGColor);
oContext.SetFillColor (this.oRectColor.CGColor);

RectangleF oRect = this.Bounds;

float fRadius = this.CornerRadius;
float fWidth = oRect.Width;
float fHeight = oRect.Height;

// Make sure corner radius isn't larger than half the shorter side.
if (fRadius > fWidth / 2.0f)
{
fRadius = fWidth / 2.0f;
}
if (fRadius > fHeight / 2.0f)
{
fRadius = fHeight / 2.0f;
}

float fMinX = oRect.GetMinX ();
float fMidX = oRect.GetMidX ();
float fMaxX = oRect.GetMaxX ();
float fMinY = oRect.GetMinY ();
float fMidY = oRect.GetMidY ();
float fMaxY = oRect.GetMaxY ();

// Move to left middle.
oContext.MoveTo (fMinX, fMidY);

// Arc to top middle.
oContext.AddArcToPoint (fMinX, fMinY, fMidX, fMinY, (this.RoundCorners & ROUND_CORNERS.TopLeft) == ROUND_CORNERS.TopLeft ? fRadius : 0);
// Arc to right middle.
oContext.AddArcToPoint (fMaxX, fMinY, fMaxX, fMidY, (this.RoundCorners & ROUND_CORNERS.TopRight) == ROUND_CORNERS.TopRight ? fRadius : 0);
// Arc to bottom middle.
oContext.AddArcToPoint (fMaxX, fMaxY, fMidX, fMaxY, (this.RoundCorners & ROUND_CORNERS.BottomRight) == ROUND_CORNERS.BottomRight ? fRadius : 0);
// Arc to left middle.
oContext.AddArcToPoint (fMinX, fMaxY, fMinX, fMidY, (this.RoundCorners & ROUND_CORNERS.BottomLeft) == ROUND_CORNERS.BottomLeft ? fRadius : 0);

// Draw the path.
oContext.ClosePath ();
oContext.DrawPath (CGPathDrawingMode.FillStroke);
}
}

编辑:

这里有一段代码演示了如何使用 CALayer 解决它。

private void UpdateMask()
{
UIBezierPath oMaskPath = UIBezierPath.FromRoundedRect (this.Bounds, this.eRoundedCorners, new SizeF (this.fCornerRadius, this.fCornerRadius));

CAShapeLayer oMaskLayer = new CAShapeLayer ();
oMaskLayer.Frame = this.Bounds;
oMaskLayer.Path = oMaskPath.CGPath;
this.Layer.Mask = oMaskLayer;
}

最佳答案

我还没有尝试过,但我认为你可以使用 CALayer 的 mask 属性来做到这一点。您必须将圆角矩形绘制到一个层中,该层被设置为 View 层的 mask 。

关于ios - 带圆角的 UIView : how to clip subviews correctly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035611/

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