ios – 填充后不能笔画路径

前端之家收集整理的这篇文章主要介绍了ios – 填充后不能笔画路径前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面的代码很好地创建了一个由CGRect(rectRect)定义的圆角矩形.

它很好,但我没有中风.任何想法为什么我看不到中风?

  1. -(void)drawRect:(CGRect)rect {
  2.  
  3. CGContextRef ctx = UIGraphicsGetCurrentContext();
  4.  
  5. CGContextSetRGBFillColor(ctx,0.4);
  6. CGContextSetRGBStrokeColor(ctx,1,1);
  7. CGContextSetLineWidth(ctx,4.0);
  8.  
  9. float fw,fh;
  10. rect = rectRect;
  11. float ovalWidth = 12;
  12. float ovalHeight = 12;
  13.  
  14. if (ovalWidth == 0 || ovalHeight == 0) {
  15. CGContextAddRect(ctx,rect);
  16. return;
  17. }
  18.  
  19. CGContextTranslateCTM (ctx,CGRectGetMinX(rect),CGRectGetMinY(rect));
  20. CGContextScaleCTM (ctx,ovalWidth,ovalHeight);
  21. fw = CGRectGetWidth (rect) / ovalWidth;
  22. fh = CGRectGetHeight (rect) / ovalHeight;
  23. CGContextMoveToPoint(ctx,fw,fh/2);
  24. CGContextAddArcToPoint(ctx,fh,fw/2,1);
  25. CGContextAddArcToPoint(ctx,fh/2,1);
  26. CGContextClosePath(ctx);
  27.  
  28. CGContextFillPath(ctx);
  29. CGContextStrokePath(ctx);
  30.  
  31. }

解决方法

当您绘制路径时,通过抚摸它或通过填充它,图形上下文将其路径重置为空.所以在你调用CGContextFillPath之后,上下文没有一个笔画的路径.

您可以使用CGContextDrawPath函数在一次调用中同时执行此操作:

  1. CGContextDrawPath(ctx,kCGPathFillStroke);

kCGPathFillStroke常数告诉Core Graphics填充路径,然后将其描边.

另一方面,您可以使用UIBezierPath和UIColor来大大减少代码量:

  1. -(void)drawRect:(CGRect)rect {
  2. [[UIColor colorWithWhite:0 alpha:0.4] setFill];
  3. [[UIColor whiteColor] setStroke];
  4.  
  5. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rectRect cornerRadius:12];
  6. path.lineWidth = 4;
  7. [path fill];
  8. [path stroke];
  9. }

猜你在找的iOS相关文章