Why do lines smaller than 1.0pts not render correctly on non-retina screens?
Asked Answered
S

2

9
self.layer.borderWidth = 0.5;

on a UIButton or UITextField render fine on a retina screen, but on a non-retina screen only the top and left borders render while the right and bottom borders do not render.

I assume it has something to do with dpi of the screen and how sub point lines are drawn, but it's possible that there is a better explanation.

Question: I'd like to know if it's possible to have all sides of a UIView's border show as expected on both retina and non-retina screens with borderWidth set to 0.5.

Salazar answered 12/6, 2013 at 21:2 Comment(1)
On retina, half 0.5 points is 1 pixel. A 1 pixel border is a perfectly coherent and unambiguous concept. On non-retina, on the other hand, 0.5 points is half a pixel. Exactly what result would you expect from asking the framework to draw a half-pixel border?Joejoeann
J
9

If you want a single pixel (not point) line always, you'll have to use a different border width depending on the scale of the screen.

E.g.:

CGFloat scale = [[UIScreen mainScreen] scale];
if (scale == 2.0)  { 
    // retina screen;
    self.layer.borderWidth = 0.5;
} else {
    // non-retina screen
    self.layer.borderWidth = 1.0;
}
Jupon answered 12/6, 2013 at 21:34 Comment(2)
this may be an acceptable answer, but do you have any idea what causes the code in my question to cause the right and bottom borders to not show or possibly get clipped?Salazar
CGFloat height = 1 / [[UIScreen mainScreen] scale]; or let height = 1 / UIScreen.mainScreen().scale for Swift 2.2Fiddlestick
I
5

Now that multiple scales are supported (@3x) it is probably better to write Matt's answer as this:

CGFloat scale = [[UIScreen mainScreen] scale];
CGFloat width = scale > 0.0 ? 1.0 / scale : 1.0;
[self.layer setBorderWidth:width];
Ivett answered 22/11, 2014 at 0:25 Comment(2)
I guess you need to remove that 'f' suffix if you are compiling with 64 bit? From what I understand, CGFloat is double on 64 bitKentledge
@kalehv Yup, fixed example to not use suffixes.Ivett

© 2022 - 2024 — McMap. All rights reserved.