How to convert between vector_float2 and CGPoint*?
Asked Answered
E

2

6

What's the easiest/fastest way to convert between vector_float2 and CGPoint* in Objective-C?

Does Apple provide any built-in functionality for this kind of type conversion? I noticed in 2-3 places in sample apps they just call CGPointMake() etc. to make the conversion

Is it possible to simply cast a CGPoint* to vector_float2 and vice versa? Is it safe to do so?


Update: obviously the solution is:

vector_float2 v = (vector_float2){(float)point.x, (float)point.y};
CGPoint p = CGPointMake(v.x, v.y);

But this is cumbersome if you need to do so frequently, and more so if there's a C array of either vector_float2* or CGPoint*. So I'm looking for already-existing solutions or very simple alternatives that I may be overlooking.

Eupheemia answered 10/7, 2015 at 14:35 Comment(2)
What about writing a function CGPointMakeFromFloat2 ?Inertia
Yes, that option exists of course. But I wonder if there's already something built in somehow somewhere?Eupheemia
Y
3

I tried to simply extend CGPoint but couldnt seem to import vector_float2; not even with the bridging header file.

// Doesn't work!!
extension CGPoint {
    init(vector: vector_float2)
    {
        self.x = CGFloat(vector.x)
        self.y = CGFloat(vector.y)
    }
}

You do have several options though. You can extend Float with a calculated var that returns a CGFloat and extend GKAgent2D to convert it's position to a CGPoint:

extension Float {
    var f: CGFloat { return CGFloat(self) }
}

extension GKAgent2D {
    var cgposition: CGPoint {
        return CGPoint(x: self.position.x.f, y: self.position.y.f)
    }
}

You can also extend CGPoint itself to accept two Float's:

extension CGPoint {
    init(x: Float, y: Float) {
        self.x = CGFloat(x)
        self.y = CGFloat(y)
    }
}

extension GKAgent2D {
    var cgposition: CGPoint {
         // Note that the ".f" is gone from the example above
        return CGPoint(x: self.position.x, y: self.position.y)
    }
}

In both cases, you can use it like this:

let agent = GKAgent2D()
let point = agent.cgposition
Yentai answered 11/7, 2015 at 2:58 Comment(1)
Sorry, I forgot the Objective-C tag. But nice example for encapsulating the conversion within the types.Eupheemia
C
2

Example:

CGPoint p                   = CGPointMake(1.0f, 1.0f);
vector_float2 v             = simd_make_float2(p.x, p.y);
CGPoint x                   = CGPointMake(v[0], v[1]);
Concinnate answered 28/5, 2019 at 14:2 Comment(1)
This doesn't compile for meRiff

© 2022 - 2024 — McMap. All rights reserved.