NSBezierPath绘制圆角矩形的圆角不够圆滑?

在Macos应用开发过程中,使用OC语言编码,效果是:圆角的线宽 比 边框的 大或者浓。

经过大量查询,发现:如果圆角矩形宽高和View的宽高一样大,就导致圆角矩形的边框线有一半在View外面而被裁剪。

调整后的代码如下:

- (void)drawRect:(NSRect)dirtyRect {
  const CGFloat cornerRadius = 8.0;
  const CGFloat lineWidth = 2.0;
  [[NSColor colorWithRed:(140.0/255.0) green:(171.0/255.0) blue:(239.0/255.0) alpha:1.0] setStroke];
  
  
  // 绘制圆角矩形 - 第1种方法。
  NSBezierPath *bezierPath = [NSBezierPath bezierPathWithRoundedRect:CGRectInset(dirtyRect, lineWidth/2, lineWidth/2) xRadius:cornerRadius yRadius:cornerRadius];
  [bezierPath setLineWidth:lineWidth];
  [bezierPath stroke];
  
  
  // // 绘制圆角矩形 - 第2种方法。
  // CGFloat top = CGRectGetMinY(dirtyRect) + lineWidth/2;
  // CGFloat bottom = CGRectGetMaxY(dirtyRect) - lineWidth/2;
  // CGFloat left = CGRectGetMinX(dirtyRect) + lineWidth/2;
  // CGFloat right = CGRectGetMaxX(dirtyRect) - lineWidth/2;
  // CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] CGContext];
  // CGContextBeginPath(context);
  // CGContextMoveToPoint(context, left, top+cornerRadius);
  // CGContextAddArcToPoint(context, left, top, left+cornerRadius, top, cornerRadius);
  // CGContextAddArcToPoint(context, right, top, right, top+cornerRadius, cornerRadius);
  // CGContextAddArcToPoint(context, right, bottom, right-cornerRadius, bottom, cornerRadius);
  // CGContextAddArcToPoint(context, left, bottom, left, bottom-cornerRadius, cornerRadius);
  // CGContextSetLineWidth(context, lineWidth);
  // CGContextClosePath(context);
  // CGContextDrawPath(context, kCGPathStroke);
}

参考链接:

https://outofmemory.cn/web/1018338.html    

https://www.coder.work/article/2362973    。

你可能感兴趣的:(IT_OC开发和swift开发,前端,objective-c)