What is the secret behind "contentScaleFactor" of UIView when used with CATiledLayer?

BastiBen picture BastiBen · Mar 11, 2011 · Viewed 19.2k times · Source

Greetings,

I'm working on an application inspired by the "ZoomingPDFViewer" example that comes with the iOS SDK. At some point I found the following bit of code:

// to handle the interaction between CATiledLayer and high resolution
// screens, we need to manually set the tiling view's 
// contentScaleFactor to 1.0. (If we omitted this, it would be 2.0 
// on high resolution screens, which would cause the CATiledLayer 
// to ask us for tiles of the wrong scales.)
pageContentView.contentScaleFactor = 1.0;

I tried to learn more about contentScaleFactor and what it does. After reading everything of Apple's documentation that mentioned it, I searched Google and never found a definite answer to what it actually does.

Here are a few things I'm curious about:

  1. It seems that contentScaleFactor has some kind of effect on the graphics context when a UIView's/CALayer's contents are being drawn. This seems to be relevant to high resolution displays (like the Retina Display). What kind of effect does contentScaleFactor really have and on what?

  2. When using a UIScrollView and setting it up to zoom, let's say, my contentView; all subviews of contentView are being scaled, too. How does this work? Which properties does UIScrollView modify to make even video players become blurry and scale up?

TL;DR: How does UIScrollView's zooming feature work "under the hood"? I want to understand how it works so I can write proper code.

Any hints and explanation is highly appreciated! :)

Answer

Luis picture Luis · Aug 20, 2011

Coordinates are expressed in points not pixels. contentScaleFactor defines the relation between point and pixels: if it is 1, points and pixels are the same, but if it is 2 (like retina displays ) it means that every point has two pixels.

In normal drawing, working with points means that you don't have to worry about resolutions: in iphone 3 (scaleFactor 1) and iphone4 (scaleFactor 2 and 2x resolution), you can use the same coordinates and drawing code. However, if your are drawing a image (directly, as a texture...) and just using normal coordinates (points), you can't trust that pixel to point map is 1 to 1. If you do, then every pixel of the image will correspond to 1 point but 4 pixels if scaleFactor is 2 (2 in x direction, 2 in y) so images could became a bit blurred

Working with CATiledLayer you can have some unexpected results with scalefactor 2. I guess that having the UIView a contentScaleFactor==2 and the layer a contentScale==2 confuse the system and sometimes multiplies the scale. Maybe something similar happens with Scrollview.

Hope this clarifies it a bit