我想在我的UIView子类上绘制一个矩形,并且除线条的宽度加倍外,所有东西都在工作(我使用的是iPhone模拟器atm,Retina版本)。在iPhone上用Core Graphics绘制一个矩形
这是drawRect方法:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect innerRect = CGRectInset(rect, 5, 5);
CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGContextSetLineWidth(context, 2);
CGContextMoveToPoint(context, CGRectGetMinX(innerRect), CGRectGetMinY(innerRect));
CGContextAddLineToPoint(context, CGRectGetMaxX(innerRect), CGRectGetMinY(innerRect));
CGContextAddLineToPoint(context, CGRectGetMaxX(innerRect), CGRectGetMaxY(innerRect));
CGContextAddLineToPoint(context, CGRectGetMinX(innerRect), CGRectGetMaxY(innerRect));
CGContextClosePath(context);
CGContextStrokePath(context);
}
此代码绘制一个矩形在正确的位置,但与宽度4像素,而不是指定的2px的。
寻找在互联网上,我看我可能需要设置比例因子,所以我尝试添加:
self.contentScaleFactor = [UIScreen mainScreen].scale;
self.layer.contentsScale = [UIScreen mainScreen].scale;
在方法的开始,当没有工作,我想:
self.contentScaleFactor = 2;
self.layer.contentsScale = 2;
(如2是应该由对视网膜显示scale
方法返回的数) 而这也不能工作。
这只是模拟器的一个问题,当我在设备上运行它时会被修复吗? (我把它升级到5.1,但忘了更新Xcode,所以我现在2小时进入7小时等待Xcode更新完成下载)
还是有东西我失踪了?
您可以使用[CGContextStrokeRectWithWidth函数]保存大量代码(http://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/Reference/reference.html#// apple_ref/C/FUNC/CGContextStrokeRectWithWidth)。 –
@PeterHosey,我知道,我实际上画了一个圆角矩形,我刚刚摆脱了弧线代码并简化了坐标,使问题更容易阅读。 –