【问题标题】:How do I create a CGRect from a CGPoint and CGSize?如何从 CGPoint 和 CGSize 创建 CGRect?
【发布时间】:2012-08-17 07:37:03
【问题描述】:

我需要从CGSizeCGPoint 的不同集合中为UIImageView 创建一个框架,这两个值总是会根据用户的选择而有所不同。那么我怎样才能使CGRect 形成CGPointCGSize?提前谢谢你。

【问题讨论】:

    标签: ios objective-c quartz-graphics cgpoint cgrectmake


    【解决方案1】:

    Objective-C 的两个不同选项:

    CGRect aRect = CGRectMake(aPoint.x, aPoint.y, aSize.width, aSize.height);
    
    CGRect aRect = { aPoint, aSize };
    

    斯威夫特 3:

    let aRect = CGRect(origin: aPoint, size: aSize)
    

    【讨论】:

    • 您在第二个示例中使用了哪种运算符?
    • 这是一个复合文字。它们是 C 的一部分,在 C99 中标准化。
    • 在 XCODE 5 中它提出:预期的表达式。这是正确的语法: (CGRect){aPoint, aSize}
    • @Pion:不,它没有。该代码运行良好,并且在最新版本的 Xcode 中不会产生任何警告。我假设您正在使用不同的代码,而不是初始化局部变量。如果您想做一些事情,例如将复合文字作为方法参数传递,则需要强制转换,但只是为了初始化局部变量,您不需要强制转换。
    • 我作为参数传递,这就是答案;)
    【解决方案2】:

    基于@Jim 的最佳答案,还可以使用这种方法构造一个 CGPoint 和一个 CGSize 。所以这些也是制作 CGRect 的有效方法:

    CGRect aRect = { {aPoint.x, aPoint.y}, aSize };
    CGrect aRect = { aPoint, {aSize.width, aSize.height} };
    CGRect aRect = { {aPoint.x, aPoint.y}, {aSize.width, aSize.height} };
    

    【讨论】:

      【解决方案3】:
      CGRectMake(yourPoint.x, yourPoint.y, yourSize.width, yourSize.height);
      

      【讨论】:

        【解决方案4】:

        您可以使用一些糖语法。例如:

        这类似于构造块,您可以将其用于更易读的代码:

        CGRect rect = ({
           CGRect customCreationRect
        
           //make some calculations for each dimention
           customCreationRect.origin.x = CGRectGetMidX(yourFrame);
           customCreationRect.origin.y = CGRectGetMaxY(someOtherFrame);
        
           customCreationRect.size.width = CGRectGetHeight(yetAnotherFrame);
           customCreationRect.size.height = 400;
        
           //By just me some variable in the end this line will
           //be assigned to the rect va
           customCreationRect;
        )}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-29
          • 2016-03-15
          相关资源
          最近更新 更多