[英]Swift Cannot assign through subscript: 'peerDeviceSettings' is a get-only property"
[英]Cannot assign to property: 'size' is a get-only property Swift
我正在尝试从URL检索图像,但我不知道为什么图像如此之大,我试图调整框架的大小,但是没有用。 我正在考虑调整图像大小,但显示
"Cannot assign to property: 'size' is a get-only property"
我使用的用于调整大小的代码是:
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)
}
我是否错误地调整了大小?
仅给出框架大小就足够了。 重要的一点是,您需要设置图像的contentMode。 当你给
if let ImageUrl = message.imageUrlLink {
receivedimg.frame.size = CGSize(width: 150, height: 150)
receivedimg.image?.contentMode = UIViewContentMode.scaleAspectFit
self.receivedimg.loadImageUsingCacheWithUrlString(ImageUrl)
}
来自Apple Document;
scaleAspectFit:通过保持纵横比来缩放内容以适合视图大小的选项。 视图边界的所有剩余区域都是透明的。
您可以在Apple文档下面查看有关contentModes的更多信息:
https://developer.apple.com/documentation/uikit/uiviewcontentmode
让我们看一下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
它说是只读的。
如果要实际调整图像的大小(而不是拉伸图像以进行显示),则可以执行以下操作:
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
}
采用:
let image: UIImage = loadImageFromSomewhere()
myUIImageView.image = resizeImageWithAspect(image: image, scaledToMaxWidth: maxWidth, maxHeight: maxHeight)
还有许多其他方法可以调整图像大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.