John D
John D

Reputation: 1545

UIImageView Resizing / Scaling - SWIFT

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.

Upvotes: 2

Views: 2853

Answers (1)

vivek takrani
vivek takrani

Reputation: 4010

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.

Upvotes: 1

Related Questions