Resize UIImage and change the size of UIImageView

后端 未结 7 1037
梦谈多话
梦谈多话 2020-12-13 04:37

I have this UIImageView and I have the values of its max height and max width. What I want to achieve is that I want to take the image (with any aspect ratio an

7条回答
  •  感动是毒
    2020-12-13 05:06

    This is the Swift equivalent for Rajneesh071's answer, using extensions

    UIImage {
      func scaleToSize(aSize :CGSize) -> UIImage {
        if (CGSizeEqualToSize(self.size, aSize)) {
          return self
        }
    
        UIGraphicsBeginImageContextWithOptions(aSize, false, 0.0)
        self.drawInRect(CGRectMake(0.0, 0.0, aSize.width, aSize.height))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
      }
    }
    

    Usage:

    let image = UIImage(named: "Icon")
    item.icon = image?.scaleToSize(CGSize(width: 30.0, height: 30.0))
    

提交回复
热议问题