skip to Main Content

I am making iOS app and created two image in photoshop. Background image (pic1) 2208×1242 px and second image (pic2) 928×195 px size.
When I run app on the device(iPhone 7 plus) in the landscape mode second image take almost half width of the device.

enter image description here
Second image placed programatically

// Constraints
    imageView.heightAnchor.constraint(equalToConstant: 195).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 928).isActive = true

    imageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

It seems that image is stretched in both directions. How to fix/avoid this issue?

1) Same issue after applying imageView.contentMode = .scaleAspectFit
enter image description here
2) If I replace this code

imageView.heightAnchor.constraint(equalToConstant: 195).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 928).isActive = true

with

imageView.frame = CGRect(x: 0, y: 0, width: 928, height: 195)

then everything works, but I don’t understand why the first version of the code (imageView.heightAnchor and imageView.widthAnchor) does not work?

2

Answers


  1. Chosen as BEST ANSWER

    I found out what caused the issue.

    heightAnchor.constraint and widthAnchor.constraint use points as size measurement not pixels, and my image size 928x195 was in pixels. So to fix issue I just needed to divide my image size by 3 for @3x image.

    From UIKit documentation:

    NSLayoutDimension - A factory class for creating size-based layout constraint objects using a fluent API. Overview Use these constraints to programatically define your layout using Auto Layout. All sizes are measured in POINTS.


  2. set image mode aspect fit

     imageView.contentMode = .scaleAspectFit
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search