【问题标题】:RubyMotion and PointersRubyMotion 和指针
【发布时间】:2012-05-11 22:01:52
【问题描述】:

我是一个 Objective-C 菜鸟,已经搜索了高和低还没有找到答案:

在我的 RubyMotion 项目中,我有一个名为 StatusGuage 的 UIView 子类,其中包含一个名为 drawLinearGradient 的方法,如下所示:

def drawLinearGradient(context, rect, startColor, endColor)
  colorspace = CGColorSpaceCreateDeviceRGB()
  locations = [0.0, 1.0]
  # colors = NSArray.arrayWithObjects(startColor, endColor, nil)
  # ptrColors = Pointer.new(:object, colors)
  colors = [startColor, endColor, nil]
  # CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef) colors, locations);
  CGGradientCreateWithColors(colorspace, colors, locations)
end

我想知道如何调用 CGGradientCreateWithColors。它显然需要一个 (CFArrayRef) 指针,但我不知道如何将它传递进去。我尝试过的迭代之一被注释掉了。

这是错误信息:

2012-05-11 16:57:36.331 HughesNetMeter[34906:17903] 
*** Terminating app due to uncaught exception 'TypeError', 
  reason: 'status_guage.rb:43:in `drawLinearGradient:': expected 
  instance of Pointer, got `[0.0, 1.0]' (Array) (TypeError)
    from status_guage.rb:13:in `drawRect:'

感谢您的帮助。

【问题讨论】:

    标签: ios ruby rubymotion


    【解决方案1】:

    有几件事。错误不是在谈论颜色,而是指const CGFloat locations[] 参数。

    这应该是一个可以这样实现的指针(Reference on Pointer class)

    locations = Pointer.new(:float, 2)
    locations[1] = 1.0
    

    接下来您的阵列不需要nil 终止。在 Ruby 中,这将创建一个包含 3 个对象的数组,这不是您想要的,因为它很可能会导致 CGGradientCreateWithColors() 函数搞砸


    这看起来像 http://www.raywenderlich.com/ 中的示例,所以这是其余的示例

    def drawLinearGradient(context, rect, startColor, endColor)
      colorspace = CGColorSpaceCreateDeviceRGB()
      locations = Pointer.new(:float, 2)
      locations[1] = 1.0
    
      colors = [startColor, endColor]
      gradient = CGGradientCreateWithColors(colorspace, colors, locations)
    
      startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect))
      endPoint   = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect))
    
      CGContextSaveGState(context)
      CGContextAddRect(context, rect)
      CGContextClip(context)
      CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0)
      CGContextRestoreGState(context)
    end
    

    最后的附注

    在这种情况下甚至不需要 locations 参数,因为 CGGradientCreateWithColors() 会自动将第一个和最后一个颜色的值设置为 0.0 和 1.0。检查CGGradient Reference

    地点
    组件中提供的每种颜色的位置。每个位置必须是 0 到 1 范围内的 CGFloat 值,包括 0 到 1。如果 0 和 1 不在位置数组中,Quartz 使用提供的最接近这些位置的 0 和 1 的颜色。
    如果locations为NULL,则colors中的第一种颜色分配给位置0,incolors中的最后一种颜色分配给位置1,中间的颜色分配给它们之间等间隔的位置。

    【讨论】:

    • 保罗,非常感谢!我期待着今天尝试一下。如果您知道任何书籍或其他资源可以让我了解有关如何翻译接口 API 的更多信息,请在此处发布。翻译一些 API 文档以在 RubyMotion 中使用并不明显。再次感谢!
    • 我没有读过任何书,所以我不能真正推荐任何书籍,但有几本 MacRuby 书籍可用。同样,我还没有读过这篇文章,但听起来很有希望rubymotion-cookbook
    猜你喜欢
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多