我创建了一个覆盖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);
}
}
编辑:
这是一段代码,演示如何使用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属性来做到这一点.您必须将圆角矩形绘制到设置为视图层的掩码的图层中.