How to convert between vector_float2 and CGPoint*?

情到浓时终转凉″ 提交于 2019-12-10 18:25:50

问题


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.


回答1:


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



回答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]);


来源:https://stackoverflow.com/questions/31343504/how-to-convert-between-vector-float2-and-cgpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!