【问题标题】:Programmatically supply argument to cgpointmake or cgpoint to create cgpoints from coordinate pair以编程方式向 cgpointmake 或 cgpoint 提供参数以从坐标对创建 cgpoint
【发布时间】:2020-07-12 14:04:59
【问题描述】:

请原谅这个幼稚的问题,但有没有直接的方法可以从坐标对创建 cgpoints 而无需分别提取 x 和 y 值。

我知道你可以做到:

CGPoint point = CGPointMake(2, 3);

float x = 2;
float y = 3;

CGPoint p  = CGPointMake(x,y);

有什么方法可以直接从 (2,3) 创建一个点而不分别提取每个 x 和 y?

我问的原因是我必须从一个看起来像 [(2,3),(4,5),(6,7)] 等的坐标数组中创建很多 CGPoints。

提前感谢您的任何建议。

【问题讨论】:

  • 你问的是Objective C还是Swift?您的代码示例是 Objective C,但您的数组是 Swift 代码。
  • 任何一个都可以。很抱歉混淆了。项目同时使用。

标签: ios objective-c swift cgpoint


【解决方案1】:

mapCGPoint init 与xy 参数一起使用。

let coordinates = [(2,3),(4,5),(6,7)]
let points = coordinates.map { CGPoint(x: $0, y: $1) }
print("\(type(of: points)): \(points)") // You'll get an `[CGPoint]` although they print as normal [(x, y)] tuples array.

【讨论】:

  • 如果你将一个相同类型的元组数组映射到结果类型的可用初始值设定项,Swift 可以推断出正确的初始值设定项。顺便说一句,从 Swift 3 开始,这可以写成CGPoint(x: $0, y: $1)。因此,正如您在下面我的帖子中看到的,您只需将 CGPoint 初始化程序传递给 map 方法
  • 是的,所有这些工作。只需要在可读性和最佳实践之间找到完美的平衡。初学者甚至会将闭包参数命名为(x, y) in 并使用它。
【解决方案2】:

好吧,如果你有戏剧天赋,也许是这样的

        // One big array
        float *   p1 = ( float [] ){ 1, 2, 3, 4, 5, 6, 7, 8 };
        float * end1 = p1 + 8;

        while ( p1 < end1 )
        {
            CGPoint point = CGPointMake ( * p1, * ( p1 + 1 ) );
            p1 += 2;

            NSLog ( @"Point ( %f, %f )", point.x, point.y );
        }

        // Array of 2D tuples
        // Not much difference though, maybe easier on the eyes?
        float *   p2 = ( float * )( float [][ 2 ] ){ { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
        float * end2 = p2 + 8;

        while ( p2 < end2 )
        {
            CGPoint point = CGPointMake( * p2, * ( p2 + 1 ) );
            p2 += 2;

            NSLog ( @"Point ( %f, %f )", point.x, point.y );
        }

【讨论】:

    【解决方案3】:

    如果你映射一个与结果类型的可用初始化器相同类型的元组数组,Swift 可以推断出正确的初始化器:

    let points = [(2,3),(4,5),(6,7)].map(CGPoint.init)
    

    【讨论】:

      【解决方案4】:

      Objective C 的解决方案可能如下所示:

      CGFloat pointValues[] = {
          2, 3,
          4, 5,
          6, 7
      };
      
      for(int i = 0; i < sizeof(pointValues) / sizeof(CGFloat); i += 2) {
          CGPoint p = CGPointMake(pointValues[i], pointValues[i + 1]);
          // Do something with 'p'...
      }
      

      pointValues 数组是每个点的 x 和 y 值的一维数组。

      或者,如果你可以使用 Objective C++,你可以简单地这样做:

      CGPoint points[] {
          { 2, 3 },
          { 4, 5 },
          { 6, 7 }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多