[英]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. 我正在尝试从URL检索图像,但我不知道为什么图像如此之大,我试图调整框架的大小,但是没有用。 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)
}
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.
重要的一点是,您需要设置图像的contentMode。 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; 来自Apple Document;
scaleAspectFit: The option to scale the content to fit the size of the view by maintaining the aspect ratio.
scaleAspectFit:通过保持纵横比来缩放内容以适合视图大小的选项。 Any remaining area of the view's bounds is transparent.
视图边界的所有剩余区域都是透明的。
You can check below Apple Document for more information about contentModes: 您可以在Apple文档下面查看有关contentModes的更多信息:
https://developer.apple.com/documentation/uikit/uiviewcontentmode https://developer.apple.com/documentation/uikit/uiviewcontentmode
Let's look on the UIIMage.size
property we'll see: 让我们看一下
UIIMage.size
属性,我们将看到:
@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. 还有许多其他方法可以调整图像大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.