视图有一个transform属性,它描述了应该如何绘制该视图。
该属性是CGAffineTransform结构体,它代表了3 x 3的变换矩阵(线性代数)。
下面的代码让两个矩形视图旋转45度
(Objective-C代码)
UIView* v1 = [[UIView alloc] initWithFrame:CGRectMake(113, 111, 132, 194)]; v1.backgroundColor = [UIColor colorWithRed:1 green:.4 blue:1 alpha:1]; UIView* v2 = [[UIView alloc] initWithFrame:CGRectInset(v1.bounds, 10, 10)]; v2.backgroundColor = [UIColor colorWithRed:.5 green:1 blue:0 alpha:1]; [mainview addSubview: v1]; [v1 addSubview: v2]; v1.transform = CGAffineTransformMakeRotation(45 * M_PI/180.0);
(Swift代码 iOS9)
let v1 = UIView(frame:CGRectMake(113, 111, 132, 194)) v1.backgroundColor = UIColor(red: 1, green: 0.4, blue: 1, alpha: 1) let v2 = UIView(frame:v1.bounds.insetBy(dx: 10, dy: 10)) v2.backgroundColor = UIColor(red: 0.5, green: 1, blue: 0, alpha: 1) mainview.addSubview(v1) v1.addSubview(v2) v1.transform = CGAffineTransformMakeRotation(45 * CGFloat(M_PI)/180.0)
记住:对父视图进行转换,子视图会跟着动。
运行结果:
子视图先平移,再旋转
v2.transform = CGAffineTransformMakeTranslation(100, 0); v2.transform = CGAffineTransformRotate(v2.transform, 45 * M_PI/180.0);
子视图先旋转,再平移
v2.transform = CGAffineTransformMakeRotation(45 * M_PI/180.0); v2.transform = CGAffineTransformTranslate(v2.transform, 100, 0); Transform
变形变换
v1.transform = CGAffineTransformMake(1, 0, -0.2, 1, 0, 0);
时间: 2024-10-23 22:25:56