【问题标题】:UIImageView AlignmentUIImageView 对齐
【发布时间】:2016-09-05 20:28:58
【问题描述】:

我在 tableviewcell 中有一个 UIImageView,并将内容模式设置为 scaleAspectFill:

let imageSize = CGSize(width: 70, height: 70)
MenuImage.contentMode = .scaleAspectFill

if(self.reuseIdentifier == "cell1") {
    MenuImage.image = UIImage.imageWithIonicon(.Map, color: UIColor.white, iconSize: 70, imageSize: imageSize)
}
else if (self.reuseIdentifier == "cell2") {
    MenuImage.image = UIImage.imageWithIonicon(.iOSPerson, color: UIColor.white, iconSize: 70, imageSize: imageSize)

}
else if (self.reuseIdentifier == "cell3") {
    MenuImage.image = UIImage.imageWithIonicon(.iOSHelp, color: UIColor.white, iconSize: 70, imageSize: imageSize)
}

虽然这使图像非常适合单元格,但图像似乎与底部对齐。有没有办法让它在 UIImageView 中垂直居中(棕色背景只是为了检查图像视图的大小)

【问题讨论】:

  • .scaleAspectFit 有什么问题?
  • 两者似乎产生了相似的结果(与底部对齐)

标签: ios swift uiimageview nslayoutconstraint


【解决方案1】:

根据This,为了修复垂直对齐,您需要在“ionicons.swift”文件中更改此行:

attString.drawInRect(CGRect(x: (imageSize.width / 2) - boundingRect.size.width / 2, y: (imageSize.height / 2) - boundingRect.size.height / 2, width: imageSize.width, height: imageSize.height))

attString.drawInRect(CGRect(x: (imageSize.width / 2) - (boundingRect.size.width / 2), y: (imageSize.height / 2) - (iconSize / 2), width: imageSize.width, height: imageSize.height))

*Swift 3.0 版本,替换为:

attString.draw(in: CGRect(x: (imageSize.width / 2) - boundingRect.size.width / 2, y: (imageSize.height / 2) - boundingRect.size.height / 2, width: imageSize.width, height: imageSize.height))

attString.draw(in: CGRect(x: (imageSize.width / 2) - (boundingRect.size.width / 2), y: (imageSize.height / 2) - (iconSize / 2), width: imageSize.width, height: imageSize.height))

【讨论】:

  • 工作得很好,谢谢。甚至没有想过这是 IocIcons 的问题
【解决方案2】:

这是一个关于约束和锚点的例子:

self.addSubview(containerView)
containerView.addSubview(yourImageView)

containerView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor).active=true
containerView.leftAnchor.constraintEqualToAnchor(self.leftAnchor).active=true

yourImageView.topAnchor.constraintEqualToAnchor(containerView.topAnchor).active=true
yourImageView.leftAnchor.constraintEqualToAnchor(containerView.leftAnchor).active=true
yourImageView.widthAnchor.constraintEqualToConstant(70).active=true
yourImageView.heightAnchor.constraintEqualToConstant(70).active=true

【讨论】:

  • 谢谢,我一开始就是这么想的(这就是为什么我用 MenuImage.backgroundColor = UIColor.brown 将 UIImageView 更改为棕色背景的原因)。 UIImageView 本身似乎是正确的大小并且在正确的位置,当以编程方式添加图像时,实际图像与 UIImageView 的底部对齐。我已经尝试了您的建议(对 Swift 3.0 进行了一些更改),但实际图像仍未在视图中居中。
猜你喜欢
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多