Search code examples
ioscore-graphicsrubymotion

Can I set the UIGraphics CurrentContext as a property Oriented in iOS


I'm writing my application using Rubymotion rather than Objective-C/Xcode.

I find that a lot of Objective-C is written a lot more like procedural code than object oriented and I'm trying to keep my code neater and simpler than I see in most examples.

In saying that, is there any reason why I can't set the CurrentContext of a custom view as a method or property within my class? That is:

def drawRect(rect)
  context = UIGraphicsGetCurrentContext()
  redColor = UIColor.colorWithRed(1.0, green: 0.0, blue: 0.0, alpha:1.0)
  CGContextSetFillColorWithColor(context, redColor.CGColor)
  CGContextFillRect(context, self.bounds)

  # more drawing here ... 
end

Would become:

def drawRect(rect)
  setBackgroundRed
  # call more private methods to draw other stuff here
end

private

def context
  @context ||= UIGraphicsGetCurrentContext()
end

def setBackgroundRed
  CGContextSetFillColorWithColor(context, redColor)
  CGContextFillRect(context, bounds)
end

def redColor
  UIColor.colorWithRed(1.0, green: 0.0, blue: 0.0, alpha:1.0).CGColor
end

Thanks!


Solution

  • It is inadvisable to store the context pointer across calls to drawRect. Each call to drawRect should make its own call to UIGraphicsGetCurrentContext() to get the context pointer. From there, pass it where it needs to go. You could do the following:

    def drawRect(rect)
      context = UIGraphicsGetCurrentContext()
      setBackgroundRed(context)
      # call more private methods to draw other stuff here
    end
    
    private
    
    def setBackgroundRed(context)
      CGContextSetFillColorWithColor(context, redColor)
      CGContextFillRect(context, bounds)
    end
    
    def redColor
      UIColor.colorWithRed(1.0, green: 0.0, blue: 0.0, alpha:1.0).CGColor
    end