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

博客讲述在Macos应用开发中用OC语言编码时,出现圆角线宽比边框大或浓的情况。经查询发现,当圆角矩形宽高与View宽高一致,圆角矩形边框线一半会在View外被裁剪,并给出调整后的代码及参考链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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    。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值