2

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.

John D
  • 1,435
  • 2
  • 16
  • 24

1 Answers1

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.

vivek takrani
  • 3,858
  • 2
  • 19
  • 33
  • Seems like a good enough solution for me. What I did though was scale the uiimage to the uiimageview's height and just switched between .center, .left and .right. Will take your's as an answer though. – John D Dec 01 '15 at 19:17