【问题标题】:Converting CGPoint to GLKVector2 in Objective-C在 Objective-C 中将 CGPoint 转换为 GLKVector2
【发布时间】:2011-11-24 20:05:31
【问题描述】:

简单的问题。将 CGPoint 转换为 GLKVector 的最佳方法是什么?

这些结构是相同的,因此能够重新解释_cast 或 memcpy 或类似的东西会很好。我下面的解决方案有效,但似乎不是最佳的。我在堆栈上创建一个 GLKVector2 分配每个成员,然后将其作为一个值返回,然后将其分配给另一个 GLKVector。

它不会破坏银行或其他任何东西,但必须有一种更简洁的方法来做到这一点?

GLKVector2 Vector2FromPoint(CGPoint point)
{
    GLKVector2 v;
    v.x = point.x;
    v.y = point.y;
    return v;
}

【问题讨论】:

  • 你的做法是我在google上找到的唯一可行的方法。

标签: ios xcode


【解决方案1】:

您可以尝试在这样的函数中使用 memcpy:

bool vector2ToCGPoint(GLKVector2* s, CGPoint* d) {
    memcpy(d, s, sizeof(*d));
}

但是最好有:

bool copyVector2ToCGPoint(GLKVector2* s, CGPoint* d) {
     d.x = s.x;
     d.y = s.x;
}

如果你真的想要优化,你可以选择一个宏:

#define copyS2D(S,D) (D.x = S.x, D.y = S.y)

所以你可以这样做:

CGPoint b;
GLKVector2 a;
vector2FromCGPoint(a, b);

当然,如您所知,宏不会是类型安全的...

【讨论】:

  • (抱歉格式化我无法解决,现在没有时间)谢谢你的答案。这是另一种方式:转换为 void ptr,然后转换为 GLKVector。 '#define GLKVectorMakeFromCGPoint(p) (GLKVector2)(void*)(&p)' 这很危险,因为 1. 它是一个宏 2. 您必须 100% 确保这些结构相同。仍然应该工作。 ——大卫·约翰
  • 抱歉错过了 * 应该有:GLKVector2 myVec2 = *(GLKVector2*)((void*)&myCGPoint); 或 '#define GLKVectorMakeFromCGPoint(p) *(GLKVector2)(void)(&p)'
  • 您不应该在类型之间进行转换。 GLKVector2 指定字节对齐为 8,CGPoint 没有指定。这是为了加快对矩阵和向量执行的 NEON 指令。投射会导致 NEON 操作执行速度变慢。
【解决方案2】:
GLKVector2 v = GLKVector2Make(point.x, point.y);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2011-09-18
    • 2020-10-26
    • 2016-12-17
    • 2010-11-07
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多