【问题标题】:Why does my Quartz arcs display thicker than the straight lines?为什么我的 Quartz 弧线显示的比直线粗?
【发布时间】:2009-05-22 21:21:29
【问题描述】:

我正在尝试创建一个看起来像 UIButtonTypeRoundedRect 的自定义 UIButton。在我的 drawRect: 中,我正在创建一个路径,首先调用 CGContextMoveToPoint(),然后调用 CGContextAddArc() 四个。然后我抚摸路径。但是,在生成的图像中,四个圆角明显比路径的其余部分厚。

我怀疑这与抗锯齿有关,所以我尝试使用 CGContextSetShouldAntiAlias() 将其关闭,但后来看起来更糟。我也尝试过线宽,但弧线总是比直线粗。 Apple 的 UIButtonTypeRoundedRect 看起来非常好,所以一定有可能以某种方式解决。有人知道吗?

编辑:相关代码:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);

CGContextMoveToPoint(context, rect.origin.x + kRoundedRectButtonRadius, rect.origin.y);
CGContextAddArc(context, rect.origin.x + rect.size.width - kRoundedRectButtonRadius, rect.origin.y + kRoundedRectButtonRadius, kRoundedRectButtonRadius, 3 * M_PI_2, 0, NO);
CGContextAddArc(context, rect.origin.x + rect.size.width - kRoundedRectButtonRadius, rect.origin.y + rect.size.height - kRoundedRectButtonRadius, kRoundedRectButtonRadius, 0, M_PI_2, NO);
CGContextAddArc(context, rect.origin.x + kRoundedRectButtonRadius, rect.origin.y + rect.size.height - kRoundedRectButtonRadius, kRoundedRectButtonRadius, M_PI_2, M_PI, NO);
CGContextAddArc(context, rect.origin.x + kRoundedRectButtonRadius, rect.origin.y + kRoundedRectButtonRadius, kRoundedRectButtonRadius, M_PI, 3 * M_PI_2, NO);

CGContextClosePath(context);
CGContextSetLineWidth(context, 1.7);
CGContextStrokePath(context);

【问题讨论】:

  • 也许发布代码可以帮助我们帮助您?

标签: iphone objective-c core-graphics antialiasing


【解决方案1】:

我之前在绘制自定义按钮时遇到过这种情况。您看到的行为源于可可的绘图例程在您要求它们的像素位置周围绘制线条居中。让我解释一下。

您绘制的直线落在按钮矩形的最边缘。当您的绘图例程被调用时,Cocoa 方便地将剪切区域设置为按钮矩形的确切边界,但是当您要求 Cocoa 沿边缘绘制一条线时,恰好一半的线被绘制在剪切之外矩形

您会注意到圆角的不同,因为弯曲部分完全落在剪切矩形内,因此没有任何一个被剪切掉。

现在解决方法:

让我们假设您正在绘制的线条正好是两个像素厚。这意味着在剪切矩形内绘制一个像素,在外部绘制一个像素(因此被忽略)。您所要做的就是在距离矩形中心更近一个像素处绘制线条。在自定义绘图例程的情况下,您可能正在使用:

NSRect myBounds = [self bounds];

然后从那里计算你的角点。在欧洲,使用:

NSRect myProperBounds = NSInsetRect([self bounds], 1.0, 1.0);

你应该很高兴。

【讨论】:

  • 你是个天才,我的朋友——我应该永远感激你!
  • 我不是天才,我以前也去过那里。玩得开心编码:)
  • 我的救星!非常感谢!
  • Cocoa 的 NSInsetRect() 的 iOS 等价物是 CGRectInset() 供任何感兴趣的人使用。
猜你喜欢
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-13
相关资源
最近更新 更多