我有这样的UIImage:
let imageView = UIImageView(image: image!)
imageView.contentMode = .scaleToFill
self.view.addSubview(imageView)
我想要做的是使图像全屏宽度,我尝试过scaleToFill,scaleAspectFit和scaleAspectFill它们都没有做任何事情......我做错了什么?
这是我的完整代码:
getLandGradingImage(image: imageData!) { result in
let image = UIImage(data: result)
if image != nil {
let imageView = UIImageView(image: image!)
imageView.contentMode = .scaleAspectFit
//Add Image to view
self.view.addSubview(imageView)
} else {
self.customAlert(title: "Error", message: "Unable to get images")
}
}
答案 0 :(得分:2)
let imageView = UIImageView(image: image!)
imageView.contentMode = .scaleAspectFill
imageView.frame = self.view.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(imageView)
答案 1 :(得分:2)
您必须使UIImageView
框架的大小与您要填充的区域相同。您可以通过显式设置框架或使用自动布局(推荐)来完成此操作。
方法1:
let imageView = UIImageView(image: image!)
imageView.frame = self.view.frame;
imageView.contentMode = .scaleAspectFit
//Add Image to view
self.view.addSubview(imageView)
方法2:
let imageView = UIImageView(image: image!)
imageView.contentMode = .scaleAspectFit
//Add Image to view
self.view.addSubview(imageView)
self.view.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": imageView]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": imageView]))
答案 2 :(得分:1)
您想要操纵UIImageView
的框架而不是内容模式。
试试这个:
let imageView = UIImageView(image: image!)
imageView.frame = self.view.frame
imageView.contentMode = .scaleToFill
self.view.addSubview(imageView)