ios - iPad:不同分辨率下项目的具体/准确位置

标签 ios ipad resolution ios-autolayout

我想将 UI 元素定位在图像上的特定位置,适用于所有 iPad 分辨率。 想象一个顶部有不同图标/按钮的平面图。每个图标应该位于非常特定的位置(例如,正好在厨房、地板上……)。更改设备/分辨率时(仅限 iPad),图标应根据背景/地面平面 imageView 保持在正确的位置。

查看图像(仅快速示例):最小的 iPad (9.7") 将是正确的位置。另一张图像 (12.9") 显示错误的位置。 (对于所有iPad尺寸,我只选择了两个例子)

9.7": enter image description here 12.9":enter image description here

我找不到解决这个定位问题的方法或想法。

最佳答案

您可以通过相对于“平面图” ImageView 的大小设置“灯泡”位置来实现此目的。

例如:

  • 假设您的平面图图像为 1800 x 1500,灯泡图像为 96 x 96(我是根据您发布的图像估算的)...
  • 假设左上角灯泡的中心位于 276, 486
  • 保存平面图的 imageView 为 900 x 750(原始尺寸的一半)

您将设置:

xScale = 900 / 1800 (0.5)
yScale = 750 / 1500 (0.5)

bulb width = 96 * xScale
bulb height = 96 * yScale

bulb center = 276 * xScale, 486 * yScale

以下是一些示例代码,可以帮助您入门:

class FloorPlanViewController: UIViewController {

    @IBOutlet var floorPlanView: UIImageView!

    var bulbs: [UIImageView] = [UIImageView]()

    var centers: [CGPoint] = [
        CGPoint(x: 276, y: 486),
        CGPoint(x: 276, y: 648),
        CGPoint(x: 640, y: 486),
        CGPoint(x: 640, y: 648),
        CGPoint(x: 877, y: 486),
        CGPoint(x: 877, y: 648),
        ]

    override func viewDidLoad() {
        super.viewDidLoad()

        for _ in centers {
            let v = bulbImageView()
            floorPlanView.addSubview(v)
            bulbs.append(v)
        }

    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        if let fpImage = floorPlanView.image {

            let xScale = floorPlanView.frame.width / fpImage.size.width
            let yScale = floorPlanView.frame.height / fpImage.size.height

            for i in 0..<centers.count {

                let thisCenter = centers[i]
                let thisBulb = bulbs[i]

                thisBulb.frame.size.width = 96.0 * xScale
                thisBulb.frame.size.height = 96.0 * yScale

                thisBulb.center = CGPoint(x: thisCenter.x * xScale, y: thisCenter.y * yScale)

            }
        }

    }

    func bulbImageView() -> UIImageView {
        let v = UIImageView()
        if let img = UIImage(named: "bulb96x96") {
            v.image = img
        } else {
            v.backgroundColor = .red
        }
        return v
    }

}

关于ios - iPad:不同分辨率下项目的具体/准确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55502476/

相关文章:

iphone - 将电话号码和电子邮件添加到地址簿会导致 iPhone 应用程序崩溃

ios - Swift-将数组分配给collectionviewcell中的tableview

带有水平 ScrollView 的顶部 iOS 下拉菜单

javascript - 从 HTML/Javascript 关闭 iPad Web 应用程序?

iphone - 推送通知对象

html - 当我在 Photoshop 中设计图像以作为 CSS 中的标题发布时,分辨率出现问题

CSS 根据屏幕分辨率设置不同的对齐方式

iOS 内存利用率读数

iphone - 即使新版本已获批准并准备销售,AppStore 仍会下载旧版本

ios - @3x 图像应该比原始 iPhone 图像大 3 倍还是 4 倍?