我创建了一个UIView
的子类,它覆盖drawRect:
并使用AddArcToPoint()
绘制圆角。 (我不想使用图层的角半径属性,因为我需要定义哪些角必须被舍入。)
然而我无法解决的问题是:如果我在(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, 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;
}
答案 0 :(得分:8)
我没有尝试过,但我认为你可以使用CALayer的mask属性来做到这一点。您必须将圆角矩形绘制到设置为视图图层蒙版的图层中。
答案 1 :(得分:2)
有可能(事实上,非常简单)指定特定的圆角而不求助于drawRect:
,或手动将部分圆角的矩形绘制到图层中。有关类似问题,请参阅my answer。