gpt4 book ai didi

ios - 我可以只调整 imageView 图像的大小吗?

转载 作者:行者123 更新时间:2023-11-28 11:25:20 24 4
gpt4 key购买 nike

所以我有这段代码:

override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView()
view.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.borderWidth = 5
imageView.layer.borderColor = UIColor.green.cgColor
NSLayoutConstraint.activate([
imageView.heightAnchor.constraint(equalToConstant: 200),
imageView.widthAnchor.constraint(equalToConstant: 200),
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0),
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0),
])
let image = UIImage(named: "3")
//let image = UIImage(named: "3")?.resizeImageWith(newSize: CGSize(width: 5,height: 5))
imageView.image = image
}

看起来像这样: enter image description here

我正在尝试使用此扩展名仅调整图像的大小(就像从绿色边框开始有边距一样):

func resizeImageWith(newSize: CGSize) -> UIImage {
let horizontalRatio = newSize.width / size.width
let verticalRatio = newSize.height / size.height
let ratio = min(horizontalRatio, verticalRatio)
let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}

但是当我这样使用它时:

let image = UIImage(named: "3")?.resizeImageWith(newSize: CGSize(width: 60,height: 60))

我得到以下结果: enter image description here

与此相同:

let image = UIImage(named: "3")?.resizeImageWith(newSize: CGSize(width: 5,height: 5))

图像变得最差。是否可以只调整图像的大小以便与 imageView 有边距?谢谢你! enter image description here

最佳答案

将 ImageView 内容模式更改为居中:

imageView.contentMode = .center

关于ios - 我可以只调整 imageView 图像的大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com