如何在Swift中以编程方式调整UIImageView的大小?

时间:2016-04-14 02:45:45

标签: swift uiimageview resize ios9 xcode7

我正在尝试基于设备屏幕大小以编程方式调整UIImageView的大小,但我无法使其工作。什么都没有改变。

这是我的代码:

    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

Interface Builder中的视图模式设置为“Aspect Fit”。我也使用自动布局,没有UIImageView宽度和高度的限制。

此代码有什么问题?

2 个答案:

答案 0 :(得分:0)

我通过创建这个辅助方法解决了这个问题:

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
}

用法是:

imgLogo.image = resizedImage(0.3, heightScale: 0.3)

答案 1 :(得分:-2)

将浮点数与switch语句进行比较是不可靠的。 尝试通过其型号识别手机

See this for details