【发布时间】:2011-12-23 13:13:44
【问题描述】:
我创建了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;
}
【问题讨论】:
-
有什么方法可以给圆形视图添加边框?
-
当然。在 DrawLayer 添加一个 CGPath.FromRoundedRect() 并使用黑色描边。
标签: ios cocoa-touch xamarin.ios quartz-graphics