UIView's contentScaleFactor depends on implementing drawRect:?

前端 未结 2 1490
北荒
北荒 2021-02-14 11:42

I have stumbled on a weird thing. It looks like UIView\'s contentScaleFactor is always 1, even on Retina devices, unless you implement drawRect:<

相关标签:
2条回答
  • 2021-02-14 12:05

    Presumably, if you don't override drawRect: then UIKit knows that a UIView doesn't draw anything so it takes the (presumably) fast case of having a layer that has a content scale of 1. As soon as you override drawRect: though, it knows it needs to set up a layer that is of the correct content scale that you can draw into if you want to. It doesn't know that you do nothing in drawRect: though so it can't make the same assumption as before.

    In fact all that is alluded to in the docs:

    For views that implement a custom drawRect: method and are associated with a window, the default value for this property is the scale factor associated with the screen currently displaying the view.

    Why don't you just override drawRect: and in that, draw your image? Or you could probably get away with what you're currently doing and have a stub drawRect:. Given what the docs say, I'd say that's perfectly reasonable to assume it's going to continue to work and is correct behaviour.

    0 讨论(0)
  • 2021-02-14 12:18

    Native drawing technologies, such as Core Graphics, take the current scale factor into account for you. For example, if one of your views implements a drawRect: method, UIKit automatically sets the scale factor for that view to the screen’s scale factor. In addition, UIKit automatically modifies the current transformation matrix of any graphics contexts used during drawing to take into account the view’s scale factor. Thus, any content you draw in your drawRect: method is scaled appropriately for the underlying device’s screen.

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