Post

UIGraphicsImageRenderer Scale in Tests

UIGraphicsImageRenderer Scale in Tests

錯誤

測試用 UIGraphicsImageRenderer(size:) 產生 32 x 24 圖片,但匯入後讀到:

1
96 x 72

原因是 renderer 使用目前裝置 scale。iPhone simulator 常見 scale 是 3,所以 32 x 24 point 會變成 96 x 72 pixel。

解法

測試 fixture 要固定 renderer scale:

1
2
3
4
5
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let image = UIGraphicsImageRenderer(size: size, format: format).image { context in
    // draw fixture
}

記住

只要測試會驗證 pixel width / height,就不要使用預設 scale。固定 format.scale = 1,測試結果才不會跟 simulator 裝置倍率綁在一起。

This post is licensed under CC BY 4.0 by the author.