IOS Drawing 1

在ios中,有两种基本的drawing技术。一种就是使用原生的drawing技术。此技术包括Core Graphics和UIKit框架,支持2D drawing。另一种就是使用OpenGL ES,此支持2D和3D。

 

1. Quartz在IOS中是native window server和drawing 技术的统称。

2. Core Graphics 框架是Quartz的核心,提供了用来drawing content的主要接口。

3.  UIKit有Quartz的基本特征,提供了一些集中的graphics-reated 操作

 

current transformation matrix(CTM)是一个数学矩阵。它映射当前view坐标系统的点到设备屏幕的点。当view第一次调用drawRect:方法时,CTM会被配置好。我们可以通过scaling,rotation,translation factors 去改变缺省的坐标系统。

 

改变CTM是一个很有用的技术。例如,我们想在当前drawing系统中点(20,20)处画一个10×10的正方形,则需要创建一个path,移动到点(20,20)处,接着画需要的线段。当我们需要移动此正方形到点(10,10)处时,我们如果重新绘制,此会有相当大的开销,然而当我们改变CTM时,则开销要小得多。

(游戏中的移动可能用得比较多)

 

在调用自定义的drawRect:方法之前,view对象会自动的配置好自己的drawing环境,(我们通过 UIGraphicCurrentContext 来获得当前的 drawing 上下文)因此代码可以直接的开始drawing。 作为配置的一部分,UIView会创建一个图形上下文(CGContextRef类型),此图形上下文包含了一些drawing 系统需要进行drawing的信息。
我们也可以创建自定义的图形上下文,但此一般用在创建image或者PDF文件中。

 

UIKit和Core Graphics都有绘制路径相关的API,从圆弧,直线段到基于矢量的图形。UIKit提供了UIBezierPath类,Core Graphics提供了CGPathRef类型。
   对于IOS创path的话,推荐使用UIBezierPath代替CGPath函数,除非我们需要只有Core Graphics才提供的功能,比如添加一个椭圆path。

 

在ios中,drawing 代码的coordinates和底层设备的pixel是有区别的。我们使用的是逻辑坐标空间,是用point来测量距离的。大多数时间我们使用points,但是有些时候我们可能需要知道多少个points映射到pixels中。在IOS4之后,UIScreen,UIView,UIImage,CALayer类都提供了一个scale factor,告诉我们points和pixels的关系。IOS4之前值都是1.0,现在有可能为1.0或者2.0。

e.g.: CALayer  contentsScale

The scale factor applied to the layer.

@property CGFloat contentsScale
Discussion
This value defines the mapping between the logical coordinate space of the layer (measured in points) and the physical coordinate space (measured in pixels). Higher scale factors indicate that each point in the layer is represented by more than one pixel at render time. For example, if the scale factor is 2.0 and the layer’s bounds are 50 x 50 points, the size of the bitmap used to present the layer’s content is 100 x 100 pixels.

The contentScale default value is 1.0. In certain restricted cases, the value may set the value to 2.0 on hi-dpi devices.

You can change this value as needed to indicate to Core Animation that the bitmap of the backing layer needs to be bigger or smaller. For example, if you set the contents of the view directly, you can change the value to ensure that layer’s bitmap matches the size of the image you are using.

Availability
Available in iOS 4.0 and later.

Drawing是一个相当耗费的工作,因此优化drawing code是非常重要的。下面几点将确保绘图代码尽可能优化。
   在每一个更新周期,应该只更新view上变化的部分。
   不透明的view的绘制比本分透明的view的绘制耗费的多得多,所以如果可以尽量使用不透明的view。
   在滚动的过程中尽量宠用table cell和views。

 

graphics context包含一个保存graphics states的堆栈。当Quartz创建了一个graphics context,此stack是空的。使用函数CGContextSaveGState push当前的graphics state在堆栈上。使用函数CGContextRestoreGState pop恢复到先前的graphics state。

 

posted @ 2012-04-01 13:17  姜萌芽  阅读(485)  评论(0编辑  收藏  举报