Search code examples
swiftcoordinatesavfoundationscreen

How to convert points from one device to another device


device 1

Device 1

device 2

Device 2

Device 1 is streaming video feed to device 2. When I draw a line on top of the video container view's layer above the video layer, I'd like to redraw the line on the second device on the same spot in relation to the video. Red background that is showing through is from the view that contains the video layer. The video layer's contentsGravity is set to .resizeAspectFill.

I have attempted to convert the points and redraw the line but it is off.

var targetCoord = CGPoint()
        
targetCoord.x = originCoord.x / originScreenSize.width * targetScreenSize.width
targetCoord.y = originCoord.y / originScreenSize.height * targetScreenSize.height

How can I take into accounts the differences in the top gap and the side gap(red area)? Adding the shape layer to the buffer and sending to the other device is not feasible since it's slow and the drawings need to go both ways. I am having a hard time wrapping my head around it and I'd appreciate any help!


Solution

  • First of all, I needed to get rid of the red area on both views by using AVMakeRect(aspectRatio:insideRect) to get the rect that fits the video and set the frame of the view containing the video layer. This way points will correspond exactly.

    I had the right idea for the conversion but I was using the wrong values for the width and height. Instead of using the screen size, use the size of the views containing the video layer.

    var targetCoord = CGPoint()
           
    targetCoord.x = originCoord.x / sourceViewSize.width * targetViewSize.width
    targetCoord.y = originCoord.y / sourceViewSize.height * targetViewSize.height