IOS:drawRect在角落显示1px

xge*_*86x 0 custom-controls ios

我在自定义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);}
Run Code Online (Sandbox Code Playgroud)

问题是在角落我有一个额外的像素(见附图).我究竟做错了什么?

在此输入图像描述

谢谢

rob*_*off 6

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

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

CGContextStrokeRect(context, CGRectInset(rect, 0.5, 0.5));
Run Code Online (Sandbox Code Playgroud)