Help us understand the problem. What is going on with this article?

【Swift 4】回転を伴う UIImageView で ContentMode が反映されない

More than 1 year has passed since last update.

はじめに

UIImageView の ContentMode が反映されない問題は ScrollView の上に UIImageView を置いた場合などに遭遇しやすいです。しかし、今回は UIImageView を Transform で回転させた場合に同様の現象が発生したときの解決方法をご紹介します。

ContentMode が反映されない一例

let cardView = UIImageView(image: #imageLiteral(resourceName: "sample_image"))
cardView.transform = CGAffineTransform(rotationAngle: 90 * CGFloat.pi / 180)
cardView.frame = CGRect(x: 0, y: 0, width: width, height: height)
cardView.center = self.view.center
cardView.contentMode = .scaleAspectFit
self.view.addSubview(cardView)

解決方法

Transform する前に ContentMode を指定しておくことで、回転後も ContentMode が反映された状態で表示されるようになります。

    let cardView = UIImageView(image: #imageLiteral(resourceName: "sample_image"))
+   cardView.contentMode = .scaleAspectFit
    cardView.transform = CGAffineTransform(rotationAngle: 90 * CGFloat.pi / 180)
    cardView.frame = CGRect(x: 0, y: 0, width: width, height: height)
    cardView.center = self.view.center
-   cardView.contentMode = .scaleAspectFit
    self.view.addSubview(cardView)

おわりに

間違っている箇所などありましたら、ご指摘いただけると嬉しいです。
見ていただきありがとうございます :bow:

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした