Core Graphics is not drawing a line at the correct width

前端 未结 1 1977
名媛妹妹
名媛妹妹 2021-02-04 22:27

I\'m trying to combine a border on an UIView with a line drawn in drawRect. I use for both the same width. But the problem is that sometimes the resulting width of the lines dra

1条回答
  •  抹茶落季
    2021-02-04 22:57

    I'm guessing the line you are drawing is not pixel aligned. If I'm wrong then ignore my tangent here. But it's useful information nonetheless.

    I'm going to borrow some screenshots from this WWDC 2011 video:

    "1-29 Session 129 - Practical Drawing for iOS Developers"

    I suggest you watch the whole thing. The relevent section starts around the 20:50 mark.

    Basically, imagine you want to draw a 1pt line from (1,2) to (4,2)

    enter image description here

    Core graphics will try and center it along the y value which is 2.0. This means it will try and draw the line with its top edge at y=1.5 and the bottom edge at y=2.5:

    enter image description here

    On a retina display this will work OK, because y=1.5 and y=2.5 are pixel aligned:

    enter image description here

    However on a non-retina display the graphics system will be forced to fill 2 vertical pixels at half-intensity to get the closest match it can:

    enter image description here

    Note that this effect will still be seen on retina displays when you are dealing with smaller fractional point values. So this problems can still be seen on retina displays depending on your view's frame.

    To fix this problem, any time you have an odd line width, you need to offset the point value where you draw it by 0.5. You need to offset it up/down/left/right depending on the situation.

    enter image description here

    I hope this helps. Without a screenshot it's hard to say what your problem is.

    0 讨论(0)
提交回复
热议问题