简体   繁体   English

iOS屏幕坐标和缩放

[英]iOS Screen coordinates and scaling

I'm trying to draw on top of an image in a CALayer and am having trouble with where the drawing shows up on different size displays. 我试图在CALayer中的图像上绘制,并且在绘制在不同尺寸的显示器上显示的位置时遇到麻烦。

func drawLayer(){
    let circleLayer = CAShapeLayer()
    let radius: CGFloat = 30
    let x = Thermo.frame.origin.x
    let y = Thermo.frame.origin.y
    let XX = Thermo.frame.width
    let YY = Thermo.frame.height
    print("X: \(x) Y: \(y) Width: \(XX) Height: \(YY)")
    circleLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2.0 * radius, height: 2.0 * radius)  , cornerRadius: radius).CGPath
    circleLayer.fillColor = UIColor.redColor().CGColor
    circleLayer.shadowOffset = CGSizeMake(0, 3)
    circleLayer.shadowRadius = 5.0
    circleLayer.shadowColor = UIColor.blackColor().CGColor
    circleLayer.shadowOpacity = 0.8
    circleLayer.frame = CGRectMake(0, 410, 0, 192);
    self.Thermo.layer.addSublayer(circleLayer)
    circleLayer.setNeedsDisplay()
}

That draws a circle, in the correct place ... for an iPhone 6s. 在正确的位置上画了一个圆圈...对于iPhone 6s。 But when the enclosing UIImageView component is scaled for a smaller device, well, to clearly doesn't. 但是,当将封闭的UIImageView组件缩放为较小的设备时,显然不会。 I added the print() to see what the image size, and position was and ... well, it's exactly the same on every device I run it on X: 192.0 Y: 8.0 Width: 216.0 Height: 584.0 but clearly it's being scaled by the constraints in the AuoLayout manager. 我添加了print()来查看图像的大小和位置,并且...好吧,在我在X上运行它的每台设备上它都是完全相同的:192.0 Y:8.0宽度:216.0高度:584.0,但显然它正在缩放受AuoLayout管理器中的约束。

So, my question is how can I figure out the proper radio and position for different screen sizes if I can't use the enclosing View's size and position since that seems to never change? 因此,我的问题是,如果我不能使用封闭的View的尺寸和位置,因为它似乎永远不会改变,那么我如何才能找到适合不同屏幕尺寸的合适的单选框和位置?

Here is the image I am starting with, in a UIImageView, and trying to draw over. 这是我开始在UIImageView中尝试绘制的图像。 基本图片 Im of course trying to color it in based on data from an external device. 我当然尝试根据来自外部设备的数据对其进行着色。 Any suggestions/sample code most appreciated! 任何建议/示例代码最感谢!

CALayer and its subclasses incl. CALayer及其子类,包括 CAShapeLayer have a property CAShapeLayer拥有一个属性

var contentsScale: CGFloat

From class reference : 从班级参考:

For layers you create and manage yourself, you must set the value of this property yourself based on the resolution of the screen and the content you are providing. 对于您自己创建和管理的图层,您必须根据屏幕的分辨率和所提供的内容自行设置此属性的值。 Core Animation uses the value you specify as a cue to determine how to render your content. Core Animation使用您指定的值作为提示来确定如何呈现内容。

So what you need to do is set the scale on the layer and you get the scale of the device from UIDevice class 因此,您需要做的是在图层上设置比例,然后从UIDevice类获取设备的比例

circleLayer.scale = UIScreen.mainScreen().scale

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM