0

I am trying to resize programmatically a UIImageView based on the device screen size, but I can´t make it work. Nothing changes.

Here´s my code:

    let screenSize: CGRect = UIScreen.mainScreen().bounds

    print(screenSize.height)

    imgLogo.image = AppKit.appLogo

    switch screenSize.height {
    case 736.0:
        print("iPhone 6 Plus")
        imgLogo.frame = CGRectMake(0,0, 80 ,80)
    case 667.0:
        print("iPhone 6")
        imgLogo.frame = CGRectMake(0,0, 60, 60)
    case 568.0:
        print("iPhone 5S")
        imgLogo.frame = CGRectMake(0,0, 50, 50)
    case 480.0:
        print("iPhone 4S")
        imgLogo.frame = CGRectMake(0,0, 40, 40)
    default: break

The View Mode in Interface Builder is set to "Aspect Fit". I am also using Auto Layout with no constraints to the UIImageView width and height.

What´s the problem with this code?

Marco Almeida
  • 1,285
  • 3
  • 17
  • 39

2 Answers2

0

I solved the issue by creating this helper method:

func resizedImage (widthScale: CGFloat, heightScale: CGFloat) -> UIImage {
    let img = AppKit.appLogo
    let size = CGSizeApplyAffineTransform(img.size, CGAffineTransformMakeScale(widthScale, heightScale))
    let hasAlpha = true
    let scale: CGFloat = 0.0 // Automatically use scale factor of main screen

    UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
    img.drawInRect(CGRect(origin: CGPointZero, size: size))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

Usage is:

imgLogo.image = resizedImage(0.3, heightScale: 0.3)
Marco Almeida
  • 1,285
  • 3
  • 17
  • 39
-2

Comparing floats with as your switch statement does is not reliable. Try identifying the phone by its model

See this for details

Community
  • 1
  • 1
paulvs
  • 11,963
  • 3
  • 41
  • 66
  • I don´t see the point of this since when I execute the code and change between simulators, it prints the correct device. The problem is not identifying the device model, but now making any changes to the UIImageView. – Marco Almeida Apr 14 '16 at 02:54