【问题标题】:iOS - Layout UIImageView's subview on the scaleaspectfit UIImageView's imageiOS - 在 scaleaspectfit UIImageView 的图像上布局 UIImageView 的子视图
【发布时间】:2018-03-03 05:31:34
【问题描述】:

我有 UITableView,每个单元格上都有一个具有相同视图(仅不同内容)的 UIStackView。(tableView 的单元格如下所示)

视图由上面的 UIImageView 和 UILabel 组成。 UIImageView 的内容设置为 .scaleAspectFit,因为保持比例。我在向 imageView 添加新图像层(子视图)时遇到问题,它必须与当前图像完美重叠,但我无法使用自动布局正确放置图像,因为我只知道 UIImageView 的锚点,而不知道图像的锚点(它没有t 存在)。

PS:我试过用imageview.image.size.width来设置宽高,但也没用。

当前使用自动布局添加子视图的代码:

func addStripe(){
        let stripeLayer = UIImageView(image: #imageLiteral(resourceName: "book_new"))
        imageView.addSubview(stripeLayer)

        stripeLayer.contentMode = .scaleToFill
        stripeLayer.translatesAutoresizingMaskIntoConstraints = false

        stripeLayer.topAnchor.constraint(equalTo: imageView.topAnchor).isActive = true
        stripeLayer.leadingAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true
        stripeLayer.trailingAnchor.constraint(equalTo: imageView.trailingAnchor).isActive = true

Aaaand 有 addStripe 函数的结果(错误的)

感谢大家的宝贵时间!

【问题讨论】:

  • 请查看this。它告诉您如何获得图像的最终尺寸。然后应该很容易正确地播放你的条纹。
  • @ReinhardMänner 完美运行!请添加您的评论作为答案,因为将其标记为解决方案。非常感谢。

标签: ios swift uitableview swift3 uiimageview


【解决方案1】:

我认为您应该将stripeLayer 的框架设置为等于imageView。您可以使用 UIImageView 的 init 方法执行此操作,如下所示:

let stripeLayer = UIImageView(frame: imageView.frame)
stripeLayer.image = #imageLiteral(resourceName: "book_new")
imageView.addSubview(stripeLayer.image)

希望对你有帮助

【讨论】:

  • 错了,因为 UIImage 不是视图,这意味着我不能将图像添加为子视图 :)
  • @prone666 但我使用的是 UIImageView,而不是 UIImage
  • 是的,当然,但是在您的代码 sn-p 的第 3 行,您添加了 stripeLayer.image
  • @prone666 没有。 "image" 是 UIImageView 的一个属性,你可以用它来设置 UIImageView 的图像。
【解决方案2】:

@ReinhardManner 的评论对我有帮助,而且效果很好。这一行解决了我的问题

let sizeInView = AVMakeRect(aspectRatio: imgViewFake.image.size, insideRect: imgViewFake.bounds).size

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多