Reputation: 55604
I am trying to draw a rectangle on my UIView subclass, and everything is working except for the width of the line is doubled (I'm using the iPhone Simulator atm, on the Retina version).
This is the drawRect method:
- (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);
}
This code draws a rectangle in the correct place but with width 4px, rather than the specified 2px.
Looking on the internet, I see I may have to set the scale factor, so I tried adding :
self.contentScaleFactor = [UIScreen mainScreen].scale;
self.layer.contentsScale = [UIScreen mainScreen].scale;
at the beginning of the method, and when that didn't work I tried:
self.contentScaleFactor = 2;
self.layer.contentsScale = 2;
(as 2 is the number that should be returned by the scale
method for retina displays)
And that didn't work either.
Is this just a problem with the simulator, that will be fixed when I run it on device? (I upgraded it to 5.1, but forget to update Xcode, so I'm currently 2 hours into the 7 hour wait for the Xcode update to finish downloading)
Or is there something I'm missing?
Upvotes: 1
Views: 2413
Reputation: 27147
This is correct behavior.
You are specifying a width of 2 points (not pixels). On a standard screen that would translate to 2 pixels, but on a retina display that translates to 4 pixels. You should also notice that the size of the rect you are passed does not change with standard or retina either. Apple encourages drawing be done with points not pixels.
A good reference is the "WWDC 2011 Session 129 - Practical Drawing for iOS Developers" video. While the video as a whole is informative, the meat of what your talking about starts at about 10:24 in to the video.
Upvotes: 3