首页 > 解决方案 > Setting the size of UIImageView proportionally

问题描述

I have a question about how to set the size of UIImageView based on iPhone's display size dynamically.

If the size of a display of iPhone decreases, I want to make the size of UIImageView decreased proportionally.

I'm setting lowerThumbImageView and upperThumbImageView like below for now.

override init(frame: CGRect) {
    super.init(frame: frame)

    trackLayer.rangeSlider = self
        // contentsScale: CGFloat - The scale factor applied to the layer.
        // scale: CGFloat - The natural scale factor associated with the screen.
    trackLayer.contentsScale = UIScreen.main.scale
        // UIControl -> UIView -> layer
    layer.addSublayer(trackLayer)

    lowerThumbImageView.image = thumbImageA
    addSubview(lowerThumbImageView)

    upperThumbImageView.image = thumbImageB
    addSubview(upperThumbImageView)

  }


// 1
  private func updateLayerFrames() {
        // insetBy(dx:dy:) - Returns a rectangle that is smaller or larger
        //                   than the source rectangle, with the same center point.
    trackLayer.frame = bounds.insetBy(dx: 0.0, dy: bounds.height / 3)
    trackLayer.setNeedsDisplay()
    lowerThumbImageView.frame = CGRect(origin: thumbOriginForValue(lowerValue),
                                       size: thumbImageA.size)
    upperThumbImageView.frame = CGRect(origin: thumbOriginForValue(upperValue),
                                       size: thumbImageB.size)
    CATransaction.begin()
    CATransaction.setDisableActions(true)
    CATransaction.commit()

  }
  // 2
  func positionForValue(_ value: CGFloat) -> CGFloat {

    return bounds.width * value
  }
  // 3
  private func thumbOriginForValue(_ value: CGFloat) -> CGPoint {
    let x = positionForValue(value) - thumbImageA.size.width / 2.0
    return CGPoint(x: x, y: (bounds.height * 0.001 - thumbImageA.size.height) / 2.0)
  }

Could you give me your advice?

Thanks for reading.

标签: iosuiimageviewsize

解决方案


您可以将 UIImageView 的大小设置为与任何其他视图成比例。以下是使用 Interface Builder Autolayout Constraints 执行此操作的步骤。

  1. 转到包含 UIImageView 的屏幕(界面生成器/StoryBoard/XIB)。
  2. 按下控制键 + 将鼠标从 UIImageView 拖动到 SuperView 或主视图,选择“等宽”和“等高”。
  3. 现在从 SizeInspector 的右侧,编辑“Proportional Width”约束并将其 Multiplier 值设置为 0.8,如果要将 UIImageView 的 80% 的宽度设置为 SuperView。
  4. 如果要将 UIImageView 70% 的宽度设置为 SuperView,请编辑“比例高度”约束并将其乘数设置为 0.7。

在此处输入图像描述 为了您的方便,我附上了图片。在此处输入图像描述 在此处输入图像描述


推荐阅读