简体   繁体   中英

Cannot assign to property: 'size' is a get-only property Swift

I am trying to retrieve an image from URL and I do not know why my image is so huge, I tried to resize my frame but it's of no use. I am thinking to resize my image but it shows

"Cannot assign to property: 'size' is a get-only property"

My code for resizing that I used is:

if let ImageUrl = message.imageUrlLink {

  receivedimg.frame.size = CGSize(width: 150, height: 150)
  receivedimg.image?.size = CGSize(width: 150, height: 150) // error shown here
  self.receivedimg.loadImageUsingCacheWithUrlString(ImageUrl)
}

and the output was 在此处输入图片说明

Am I resizing it wrongly?

It is enough to give just size to frame. Important point is that you need to set contentMode of image. When you giv

if let ImageUrl = message.imageUrlLink {
    receivedimg.frame.size = CGSize(width: 150, height: 150)
    receivedimg.image?.contentMode = UIViewContentMode.scaleAspectFit
    self.receivedimg.loadImageUsingCacheWithUrlString(ImageUrl)
} 

From Apple Document;

scaleAspectFit: The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view's bounds is transparent.

You can check below Apple Document for more information about contentModes:

https://developer.apple.com/documentation/uikit/uiviewcontentmode

Let's look on the UIIMage.size property we'll see:

@property(nonatomic,readonly) CGSize size; // reflects orientation setting. In iOS 4.0 and later, this is measured in points. In 3.x and

and it says read only.

If you want to actually resize the image (and not stretching it for display), you can do something like:

func resizeImageWithAspect(image: UIImage,scaledToMaxWidth width:CGFloat,maxHeight height :CGFloat)->UIImage? {
    let oldWidth = image.size.width;
    let oldHeight = image.size.height;

    let scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;

    let newHeight = oldHeight * scaleFactor;
    let newWidth = oldWidth * scaleFactor;
    let newSize = CGSize(width: newWidth, height: newHeight)

    UIGraphicsBeginImageContextWithOptions(newSize,false,UIScreen.main.scale);

    image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height));
    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage
}

use:

let image: UIImage = loadImageFromSomewhere()
myUIImageView.image = resizeImageWithAspect(image: image, scaledToMaxWidth: maxWidth, maxHeight: maxHeight)

There are a lot of other ways to resize the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM