4

我正在尝试创建一个看起来像 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);
4

1 回答 1

12

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

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

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

现在解决方案:

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

NSRect myBounds = [self bounds];

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

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

你应该很高兴。

于 2009-05-22T21:53:06.710 回答