UIView 简介(十四)transfrom属性

来源:互联网 发布:玩耍的网络语 编辑:程序博客网 时间:2024/06/06 13:56

UIView的transform属性就是一个CGAffineTransform类型的数据,默认值为CGAffineTransformIdentity。

Specifies the transform applied to the receiver, relative to the center of its bounds.

@property(nonatomic) CGAffineTransform transform
Discussion

The origin of the transform is the value of the center property, or the layer’s anchorPoint property if it was changed. (Use the layer property to get the underlying Core Animation layer object.) The default value isCGAffineTransformIdentity.

Changes to this property can be animated. Use the beginAnimations:context: class method to begin and thecommitAnimations class method to end an animation block. The default is whatever the center value is (or anchor point if changed)

Warning: If this property is not the identity transform, the value of the frame property is undefined and therefore should be ignored.


UIView的transform指示其在屏幕上的呈现方式,与Quartz的变换原点为左上角或左下角不同,UIView变换的原点为center 或layer的anchorPoint。

什么是 Transform

Transform (变化矩阵)是一种3×3的矩阵,如下图所示:

通过这个矩阵我们可以对一个坐标系统进行缩放,平移,旋转以及这两者的任意组着操作。而且矩阵的操作不具备交换律,即矩阵的操作的顺序不同会导致不同的结果。 UIView 有个 transform 的属性,通过设置该属性,我们可以实现调整该 view 在其 superView 中的大小和位置。

矩阵实现坐标变化背后的数学知识:

设x,y分别代表在原坐标系统中的位置,x',y'代表通过矩阵变化以后在新的系统中的位置。其中式1就是矩阵变化的公式,对式1进行展开以后就可以得到式2。从式2我们可以清楚的看到(x,y)到(x',y')的变化关系。

1)当c,b,tx,ty都为零时,x' = ax,y' = by;即a,d就分别代表代表x,y方向上放大的比例;当a,d都为1时,x' = x,y' = y;这个时候这个矩阵 也就是传说中的 CGAffineTransformIdentity (标准矩阵)。

2)当a,d为1,c,d为零的时候,x' = x + tx,y' = y + ty;即tx,ty分别代表x,y方向上的平移距离。

3) 前面两种情况就可以实现缩放和平移了,那么旋转如何表示呢?

假设不做平移和缩放操作,那么从原坐标系中的一点(x,y)旋转α°以后到了新的坐标系中的一点(x',y'),那么旋转矩阵如下:

展开以后就是x' = xcosα - ysinα,y' = xsinα + ycosα;

实际应用中,我们将这些变化综合起来,即可完成所有二维的矩阵变化。现在我们在回过头来看看前面设备旋转时的输出,当设备位于 Portrait 的时候由于矩阵是标准矩阵,所以没有进行打印。当转到 UIInterfaceOrientationLandscapeLeft 方向的时候,我们的设备是顺时针转了90°,这个时候矩阵应该是 (cos90°,sin90°,-sin90°,cos90°,tx,ty) ,由于未进行平移操作所以tx,ty都为0,刚好可以跟我们控制台输出:" <UIView: 0x8075390; frame = (0 0; 320 480); transform = [0, -1, 1, 0, 0, 0]; autoresize = W+H; layer = <CALayer: 0x8074980>> "一致。观察其他两个方向的输出,发现结果均和分析一致。

由此可以发现屏幕旋转其实就是通过view的矩阵变化实现,当设备监测到旋转的时候,会通知当前程序,当前程序再通知程序中的 window , window 会通知它的 rootViewController 的, rootViewController 对其 view 的 transform 进行设置,最终完成旋转。

如果我们直接将一个 view 添加到 window 上,系统将不会帮助我们完成旋操作,这个时候我们就需要自己设置该 view 的 transform 来实现旋转了。这种情况虽然比较少,但是也存在的,例如现在很多App做的利用状态栏进行消息提示的功能就是利用自己创建 window 并且自己设置 transform 来完成旋转支持的,下一篇博客会介绍如何实现这种消息通知。

0 0
原创粉丝点击