【问题标题】:How to set line width for different devices如何为不同的设备设置线宽
【发布时间】:2026-01-08 20:05:02
【问题描述】:

我正在为适用于 iPad 和 iPhone 的应用程序绘制图表。 我已经设法缩放所有维度,以便图表、轴等可以针对不同的设备正确缩放。 但我不确定如何缩放线宽。 所以如果我写:

context?.setLineWidth(4.0)

这条线在 iPhone 5 上会显得很粗,但在 iPad 上会更细。我想让它在较小的设备上看起来更薄。

【问题讨论】:

  • 尽量考虑设备的规模。 IE。 UIScreen.mainScreen().scale。对于 iPad 2 等非视网膜设备返回 1.0,对于 iPhone 5 等视网膜设备返回 2.0,对于 6 plus 和 7 plus 等返回 3.0。
  • 如果我想要一个像素线,我使用1 / UIScreen.mainScreen().scale。我实际上有一个NSLayoutConstraint 的子类,它以这种方式转换其constant,因此我可以在情节提要中设置正确的值以像素为单位
  • 这是一个使用 UIDevice 进行设备检测的不错的扩展:*.com/questions/26028918/…

标签: ios swift


【解决方案1】:

根据图形或屏幕宽度将LineWidth更改为动态值,试试这样

iPhone 5

let graphWidth = 320.0 //set screenWidth
var lineWidth = (graphWidth*(1.5/100)) // here you can change the percentage value
print("Line Width == > \(Int(lineWidth))") //Line Width == > 4

iPhone 6

let graphWidth = 375.0 // be dynamic graphWidth = graph width
var lineWidth = (graphWidth*(1.5/100))
print("Line Width == > \(Int(lineWidth))") //Line Width == > 5

【讨论】: