iOS extracts: Adding Color

 
extracts from 《Beginning iPhone Games Development》

Let’s throw some paint on the canvas. Like any good artist, Quartz 2D likes to paintoutlines before it fills in a scene. These outlines are calledpaths. The following lines ofcode create a rectangular path (the lines are numbered on the right for clarity).

CGContextBeginPath(context);                            (1)
CGContextSetRGBFillColor(context, 0,1,0,1);             (2)
CGContextAddRect(context, CGRectMake(0,0,100,200));     (3)
CGContextClosePath(context);                            (4)

As before, the API functions begin with the lettersCG. Most calls require the graphicscontext, which we went through great pains to create.CGContextBeginPath, on line 1,starts a fresh, new path in Quartz 2D. The Quartz 2D engine is like an artist with just onepair of hands. At any time, only one path is being created.

CGContextSetRGBFillColor, on line 2, specifies the color we would like to use in ourpath. Colors in Quartz 2D are specified in three unit values—a floating-point numberbetween 0 and 1—for each of red, green, and blue. A value of 0 means to use no colorfor the given color component, 0.5 means to use 50% of that color, and 1.0 means touse 100% of the color. A fourth unit value represents the opacity, where 0 means thegraphic is invisible, 0.5 means make the graphic 50% transparent, and 1 means thegraphic is completely opaque. Quartz has numerous, powerful ways to combine thesecolors for interesting effects. For now, we’ll use the default, which just adds thecomponents together to create a single green, completely opaque color:

(0 x red) + (1.0 x green) + (0.0 x blue) at an opacity of 1.0

CGContextAddRect, on line 3, adds a single rectangle to the current path. We describeour rectangle using theCGRectMakemacro. The macro is passed an origin (0,0), a width(100), and a height (200).

CGContextClosePath, on line 4, tells Quartz 2D that we’re finished with the current path,and ready to paint with it on the canvas. The following call tells Quartz to take thecurrent path, fill it in with the current color, and add it to the canvas. The first argumentis the context. The second argument is a drawing mode, one of several available. 

CGContextDrawPath(context,kCGPathFill);

Finally, being good citizens, we restore the state of the canvas with a single call:

CGContextRestoreGState(context);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值