ios – 具有圆角的UIView:如何正确剪辑子视图?

前端之家收集整理的这篇文章主要介绍了ios – 具有圆角的UIView:如何正确剪辑子视图?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个覆盖drawRect的UIView子类,并使用AddArcToPoint()绘制圆角. (我不想使用图层的角半径属性,因为我需要定义哪些角必须舍入.)
问题我不能得到:如果我添加一个子视图(0 | 0),它隐藏我的圆角.任何想法如何解决这个问题?我想要很好地剪辑.

这是绘制圆角矩形的代码.这是Monotouch,但任何开发人员都应该可以理解.

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

  1. public override void Draw (RectangleF rect)
  2. {
  3. using (var oContext = UIGraphics.GetCurrentContext())
  4. {
  5. oContext.SetLineWidth (this.StrokeWidth);
  6. oContext.SetStrokeColor (this.oStrokeColor.CGColor);
  7. oContext.SetFillColor (this.oRectColor.CGColor);
  8.  
  9. RectangleF oRect = this.Bounds;
  10.  
  11. float fRadius = this.CornerRadius;
  12. float fWidth = oRect.Width;
  13. float fHeight = oRect.Height;
  14.  
  15. // Make sure corner radius isn't larger than half the shorter side.
  16. if (fRadius > fWidth / 2.0f)
  17. {
  18. fRadius = fWidth / 2.0f;
  19. }
  20. if (fRadius > fHeight / 2.0f)
  21. {
  22. fRadius = fHeight / 2.0f;
  23. }
  24.  
  25. float fMinX = oRect.GetMinX ();
  26. float fMidX = oRect.GetMidX ();
  27. float fMaxX = oRect.GetMaxX ();
  28. float fMinY = oRect.GetMinY ();
  29. float fMidY = oRect.GetMidY ();
  30. float fMaxY = oRect.GetMaxY ();
  31.  
  32. // Move to left middle.
  33. oContext.MoveTo (fMinX,fMidY);
  34.  
  35. // Arc to top middle.
  36. oContext.AddArcToPoint (fMinX,fMinY,fMidX,(this.RoundCorners & ROUND_CORNERS.TopLeft) == ROUND_CORNERS.TopLeft ? fRadius : 0);
  37. // Arc to right middle.
  38. oContext.AddArcToPoint (fMaxX,fMaxX,fMidY,(this.RoundCorners & ROUND_CORNERS.TopRight) == ROUND_CORNERS.TopRight ? fRadius : 0);
  39. // Arc to bottom middle.
  40. oContext.AddArcToPoint (fMaxX,fMaxY,(this.RoundCorners & ROUND_CORNERS.BottomRight) == ROUND_CORNERS.BottomRight ? fRadius : 0);
  41. // Arc to left middle.
  42. oContext.AddArcToPoint (fMinX,fMinX,(this.RoundCorners & ROUND_CORNERS.BottomLeft) == ROUND_CORNERS.BottomLeft ? fRadius : 0);
  43.  
  44. // Draw the path.
  45. oContext.ClosePath ();
  46. oContext.DrawPath (CGPathDrawingMode.FillStroke);
  47. }
  48. }

编辑:

这是一段代码,演示如何使用CALayer解决它.

  1. private void UpdateMask()
  2. {
  3. UIBezierPath oMaskPath = UIBezierPath.FromRoundedRect (this.Bounds,this.eRoundedCorners,new SizeF (this.fCornerRadius,this.fCornerRadius));
  4.  
  5. CAShapeLayer oMaskLayer = new CAShapeLayer ();
  6. oMaskLayer.Frame = this.Bounds;
  7. oMaskLayer.Path = oMaskPath.CGPath;
  8. this.Layer.Mask = oMaskLayer;
  9. }

解决方法

我没有尝试过,但我认为可以使用CALayer的mask属性来做到这一点.您必须将圆角矩形绘制到设置为视图层的掩码的图层中.

猜你在找的iOS相关文章