IOS:drawRect 在角上显示 1px

标签 ios custom-controls

我在自定义 UIButton 中使用 drawRect 来绘制一个带有图像的边框按钮。代码如下:

- (void) drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();

//Draw a rectangle
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextSetStrokeColorWithColor(context, [[UIColor grayColor] CGColor]);
//Define a rectangle
CGRect drawrect = CGRectMake(CGRectGetMinX(rect),CGRectGetMinY(rect),rect.size.width,rect.size.height);

CGContextStrokeRect(context,drawrect);}

问题是在角落我得到了一个额外的像素(见附图)。我做错了什么?

enter image description here

谢谢

最佳答案

您是沿着像素的边缘绘制矩形,而不是沿着像素的中心绘制。所以你的矩形只覆盖了大多数像素的一半。在角落,它覆盖了四分之三的像素。

要沿着像素中心绘制,您必须使用半整数坐标。试试这个:

CGContextStrokeRect(context, CGRectInset(rect, 0.5, 0.5));

关于IOS:drawRect 在角上显示 1px,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9056330/

相关文章:

ios - 重复单元格背景颜色

.net - 用派生控件替换 Windows.Forms 控件的可靠/简单方法?

c# - 是否可以从控件创建 JPG?

c# - 防止 Size 属性在等于默认值时被序列化

ios - mvvmcross sqlite-PCL iOS 安全

ios - 使用核心动画对轨迹变化进行动画处理

c# - 将按钮的事件订阅到自定义控件中

C# 用户控件自定义属性

ios - 在 Swift 中调用绘图函数

ios - 如何从配置文件中获取代码签名身份的名称?