ios - 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.
解决方案
您可以将 UIImageView 的大小设置为与任何其他视图成比例。以下是使用 Interface Builder Autolayout Constraints 执行此操作的步骤。
- 转到包含 UIImageView 的屏幕(界面生成器/StoryBoard/XIB)。
- 按下控制键 + 将鼠标从 UIImageView 拖动到 SuperView 或主视图,选择“等宽”和“等高”。
- 现在从 SizeInspector 的右侧,编辑“Proportional Width”约束并将其 Multiplier 值设置为 0.8,如果要将 UIImageView 的 80% 的宽度设置为 SuperView。
- 如果要将 UIImageView 70% 的宽度设置为 SuperView,请编辑“比例高度”约束并将其乘数设置为 0.7。
推荐阅读
- twilio - Twilio:Webhook 如何访问来电的 SHAKEN/STIR 状态?
- python - Scrapy exceptions.ImportError 仅在 Scrapyrt Docker 容器中
- python - 如何将 .py 文件转换为 .exe 隐藏控制台(基于另一个 stackoverflow 的帖子)
- react-native - 如何使用硬币奖励添加奖励广告
- next.js - 在 nextJS 应用程序中,使用 SWR 通过 SSR 刷新预取数据是一种好习惯吗?
- rust - 为什么我实现 MyTrait 的具体类型不是有效的“dyn MyTrait”特征对象?
- html - 两个div之间的空格问题
- node.js - Discord.js 维基百科同人圈搜索命令未找到任何结果
- amazon-web-services - 使用用户信息从 React Native 上传 Amazon s3 存储桶中的项目
- animation - 在 Xamarin 窗体上打开/关闭 Prism IDialogService 对话框时如何控制动画