我创建了一个覆盖drawRect的UIView子类,并使用AddArcToPoint()绘制圆角. (我不想使用图层的角半径属性,因为我需要定义哪些角必须舍入.)
问题我不能得到:如果我添加一个子视图(0 | 0),它隐藏我的圆角.任何想法如何解决这个问题?我想要很好地剪辑.
问题我不能得到:如果我添加一个子视图(0 | 0),它隐藏我的圆角.任何想法如何解决这个问题?我想要很好地剪辑.
这是绘制圆角矩形的代码.这是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,(this.RoundCorners & ROUND_CORNERS.TopLeft) == ROUND_CORNERS.TopLeft ? fRadius : 0); // Arc to right middle. oContext.AddArcToPoint (fMaxX,fMaxX,fMidY,(this.RoundCorners & ROUND_CORNERS.TopRight) == ROUND_CORNERS.TopRight ? fRadius : 0); // Arc to bottom middle. oContext.AddArcToPoint (fMaxX,fMaxY,(this.RoundCorners & ROUND_CORNERS.BottomRight) == ROUND_CORNERS.BottomRight ? fRadius : 0); // Arc to left middle. oContext.AddArcToPoint (fMinX,fMinX,(this.RoundCorners & ROUND_CORNERS.BottomLeft) == ROUND_CORNERS.BottomLeft ? fRadius : 0); // Draw the path. oContext.ClosePath (); oContext.DrawPath (CGPathDrawingMode.FillStroke); } }
编辑:
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属性来做到这一点.您必须将圆角矩形绘制到设置为视图层的掩码的图层中.