I'm using SDWebImage for showing images inside cells. But it is perfect mached to frame of UImageView that I'm doing in code below:
NSString * s =[NSString stringWithFormat:@"url of image to show"];
NSURL *url = [NSURL URLWithString:s];
[cell.shopImageView sd_setImageWithURL:url];
My UIImageView is size 50x50.
For example image from url is size 990x2100 and my image is not displaying well in the frame given.
In this case when hight is bigger, I want to resize my image by proper height ratio to match width 50.
Is there a way to check image's size from url without downloading it and allocating memory in awful way?
You can fetch this data from URL header, in Swift 3.0 use below code
if let imageSource = CGImageSourceCreateWithURL(url! as CFURL, nil) {
if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary? {
let pixelWidth = imageProperties[kCGImagePropertyPixelWidth] as! Int
let pixelHeight = imageProperties[kCGImagePropertyPixelHeight] as! Int
print("the image width is: \(pixelWidth)")
print("the image height is: \(pixelHeight)")
}
}
Try messing with the different contentMode options to get the look you want. One example could be cell.shopImageView.contentMode = UIViewContentModeScaleAspectFit;
That will just make the image fit nicely, but won't actually resize the image view.
Here are your contentMode options: UIViewContentModes
An alternative could be something along the lines of this:
NSData *data = [[NSData alloc]initWithContentsOfURL:URL];
UIImage *image = [[UIImage alloc]initWithData:data];
CGFloat height = image.size.height;
CGFloat width = image.size.width;
You can then set your imageView height/width depending on the ratio of the image's height/width.
let ImageArray = ((arrFeedData[indexPath.row] as AnyObject).value(forKey: "social_media_images") as? NSArray)!
var ImageURL: String = ((ImageArray[0] as AnyObject) as? String)!
ImageURL = ImageURL.addingPercentEscapes(using: String.Encoding.ascii)!
let imageUrl = URL(string: ImageURL)
let imageData = try Data(contentsOf: imageUrl!)
let image = UIImage(data: imageData)
print("image height: \(image?.size.height)"
print("image Width: \(image?.size.width)")