如何在 vector_float2 和 CGPoint* 之间进行转换? [英] How to convert between vector_float2 and CGPoint*?
问题描述
在 Objective-C 中在 vector_float2 和 CGPoint* 之间进行转换的最简单/最快的方法是什么?
What's the easiest/fastest way to convert between vector_float2 and CGPoint* in Objective-C?
Apple 是否为这种类型转换提供任何内置功能?我注意到在示例应用程序的 2-3 个地方,他们只是调用 CGPointMake() 等来进行转换
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
是否可以简单地将 CGPoint* 转换为 vector_float2,反之亦然?这样做安全吗?
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);
但是如果您需要经常这样做,这会很麻烦,如果有 vector_float2*
或 CGPoint*
的 C 数组,则更麻烦.所以我正在寻找已经存在的解决方案或我可能忽略的非常简单的替代方案.
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.
推荐答案
我试图简单地扩展 CGPoint
但似乎无法导入 vector_float2
;甚至没有桥接头文件.
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)
}
}
不过,您确实有多种选择.您可以使用返回 CGFloat
的计算 var
扩展 Float
并扩展 GKAgent2D
以将其位置转换为 <代码>CGPoint:
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)
}
}
您也可以扩展 CGPoint
本身以接受两个 Float
:
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
这篇关于如何在 vector_float2 和 CGPoint* 之间进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!