UIImageView Resizing / Scaling - SWIFT

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-22 18:35:32

问题


I have a UIImageView that's size(width = screensize, height = 239). I now download an image that is size(width = 1366 and height = 445).

I can't use Aspect Fit (because of white background) or Scale (screws up the aspect ratio). I do want to use Aspect Fill and align it in a specific way - i.e. aspect fill on right aligned or aspect fill on left aligned. Does anyone know how to do this?

I've used different libraries like Toucan but I can't seem to get it to work. Thanks a bunch SO.


回答1:


You can use SDWebImage or Kingfisher to show placeholder image and for caching... Then in its completion block write a code to resize the imageView

@IBOutlet weak var yourImageView: UIImageView!

func loadImage(){

 SDWebImageManager.sharedManager().downloadImageWithURL(imgURL, options: SDWebImageOptions.CacheMemoryOnly, progress: { (received, expected) -> Void in

    }) { (theImage : UIImage!, error : NSError!, cacheType : SDImageCacheType!, bool : Bool, imageUrl : NSURL!) -> Void in

         let aspect = theImage.size.width / theImage.size.height

         self.aspectConstraint = NSLayoutConstraint(item: self.yourImageView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.yourImageView, attribute: NSLayoutAttribute.Height, multiplier: aspect, constant: 1.2)

         self.yourImageView.image = theImage
    }
}//loadImage


var aspectConstraint: NSLayoutConstraint? {

    willSet {

        if((aspectConstraint) != nil) {
            self.yourImageView.removeConstraint(self.aspectConstraint!)   
        }
    }

    didSet {

        if(aspectConstraint != nil) {
            self.yourImageView.addConstraint(self.aspectConstraint!)
        }

    }

}

Hope this helps.



来源:https://stackoverflow.com/questions/34023653/uiimageview-resizing-scaling-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!