我有一个关于如何根据iPhone的显示大小动态设置UIImageView大小的问题。
如果iPhone的显示尺寸减小,我想使UIImageView的尺寸成比例地减小。
我现在像下面这样设置lowerThumbImageView和upperThumbImageView。
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)
}
您能给我您的建议吗?
感谢阅读。
您可以将UIImageView的大小设置为与其他任何View成比例。这是使用“界面生成器自动布局约束”执行此操作的步骤。