Search code examples
iosuiimageviewsize

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.


Solution

  • You can set size of UIImageView proportional to any other View. Here are the steps to do it using Interface Builder Autolayout Constraints.

    1. Go to Screen containing UIImageView on (Interface Builder/StoryBoard/XIB).
    2. Press control button + drag mouse from UIImageView to SuperView or main View, Select "Equal Widths" & "Equal Heights".
    3. Now from the right side in SizeInspector, Edit "Proportional Width" constraint & set its Multiplier value to 0.8 if you want to set width of UIImageView 80% to SuperView.
    4. Edit "Proportional Height" constraint & set its Multiplier value to 0.7 if you want to set width of UIImageView 70% to SuperView.

    enter image description here I've attached images for your ease.enter image description here enter image description here