iOS UIImage 超出 UIImageView 边框

4

这里黑色边框表示UIImageView的父UIView,红色边框表示UIImageView。我正在从服务器上下载图片,但是图片超出了UIImageView的区域,如图所示。我是通过编程实现的,请您提供任何帮助将不胜感激。下面是我添加的代码块:

输入图像描述信息

let bottomView : UIView = UIView(frame: CGRect(x : 10, y: stackView.height, width: view.width * 0.75, height: view.width * 0.75 ))

view.addSubview(bottomView)

bottomView.layer.borderColor = UIColor.black.cgColor
bottomView.layer.borderWidth = 1

bottomView.translatesAutoresizingMaskIntoConstraints = false
bottomView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
bottomView.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: -20).isActive = true
bottomView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
bottomView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
bottomView.widthAnchor.constraint(equalToConstant: view.width * 0.75).isActive = true
bottomView.heightAnchor.constraint(equalToConstant: view.width * 0.75).isActive = true

let imageView : UIImageView = UIImageView(frame : CGRect(x: 0, y: 0, width: 250, height: 250 ))

 imageView.layer.borderColor = UIColor.red.cgColor
 imageView.layer.borderWidth = 1
 bottomView.addSubview(imageView)

 imageView.translatesAutoresizingMaskIntoConstraints = false
 imageView.centerXAnchor.constraint(equalTo: bottomView.centerXAnchor).isActive = true
 imageView.centerYAnchor.constraint(equalTo: bottomView.centerYAnchor).isActive = true
 imageView.widthAnchor.constraint(equalToConstant: 250).isActive = true
 imageView.heightAnchor.constraint(equalToConstant: 250).isActive = true
 imageView.downloadedFrom(link: (sizeResult?.results![0].data?.size_Chart?.mobile_image?.imageValue?.imageMain?.url)!, contentMode : .scaleAspectFill)

这个 bottomView 将会添加 UIAlertViewController。

这张图片展示了 contentMode 是 Aspect Fit。


@MahendraGP 我尝试过了,但只有一半的图像是可见的。 - Ganesh Shetty
将 contentMode 设置为 aspect fit - Arnab
@ArnabHore 它将图片缩小并向左对齐。 - Ganesh Shetty
根据我从您的图片中所理解的,您的图片右侧有很多空白...尝试使用任何像预览这样的照片编辑工具裁剪图像,然后使用它,否则您必须通过代码或从Storyboard将图像移动到imageView的右侧... - Arnab
@ArnabHore 谢谢您先生。我会检查的。 - Ganesh Shetty
显示剩余2条评论
4个回答

6

您可以使用clip与您的图像视图绑定,这将解决您的问题。 Swift:

override func viewDidLoad() {
    super.viewDidLoad()

    self.bottomView.clipsToBounds = false
    self.imageView.clipsToBounds = true
}

5

设置uiimageview的属性和内容模式:

self.imageView.clipsToBounds = true
self.imageView.contentMode = .scaleAspectFit

2

imageView?.contentMode = .scaleAspectFit

self.imageView.clipsToBounds = true

这对我很有用。


0
你的代码最后一行应该是这样的 -
imageView.downloadedFrom(link: (sizeResult?.results![0].data?.size_Chart?.mobile_image?.imageValue?.imageMain?.url)!, contentMode : .scaleAspectFit)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接