今天有闲情逸致,再来一篇
1.contents填充图片时,如果加圆角,图片会超出圆角框,即还是直角,得加一句masksToBounds(imageView加圆角则没有这样的问题):
layer.masksToBounds = YES;
2.transform.rotation旋转,直接setValue forKeyPath:
摘自文档:
You can not specify a structure field key path using Objective-C 2.0 properties. This will not work:
myLayer.transform.rotation.x=0; |
Instead you must use setValue:forKeyPath: or valueForKeyPath: as shown below:
[myLayer setValue:[NSNumber numberWithInt:0] forKeyPath:@"transform.rotation.x"]; |
注意:当设置y坐标时,直接赋值会有问题,应该先hold住当前状态,再改变(x/z则没问题),我这用的UISlider测试:
CALayer *layer=[window.layer.sublayers objectAtIndex:0];
//hold住当前状态
layer.transform = CATransform3DIdentity;
//用slider来改变,如果没hold住,当大于90度时,慢慢划动会导致一正一反反复出现…
[layer setValue:[NSNumber numberWithFloat:DegreesToRadians(slider.value)] forKeyPath:@"transform.rotation.y"];
3.进一步,摘自文档:
Modifying a Transform Using Key Paths
Core Animation extends the key-value coding protocol to allow getting and setting of the common values of a layer's CATransform3D matrix through key paths. Table 4 describes the key paths for which a layer’s transform and sublayerTransform properties are key-value coding and observing compliant.
Table 4 CATransform3D key paths
Field Key Path | Description |
rotation.x | The rotation, in radians, in the x axis. |
rotation.y | The rotation, in radians, in the y axis. |
rotation.z | The rotation, in radians, in the z axis. |
rotation | The rotation, in radians, in the z axis. This is identical to setting the rotation.z field. |
scale.x | Scale factor for the x axis. |
scale.y | Scale factor for the y axis. |
scale.z | Scale factor for the z axis. |
scale | Average of all three scale factors. |
translation.x | Translate in the x axis. |
translation.y | Translate in the y axis. |
translation.z | Translate in the z axis. |
translation | Translate in the x and y axis. Value is an NSSize or CGSize. |
(1)setValue的时候这些keyPath需加前缀transform,如transform.rotation, transform.scale,不然不反应
(2)scale在改变时,x/y同时变,二维z不变,最好也hold,slider的min值最好不要为0(或者检测到0的时候特殊处理),因为scale 0的话会导致layer不见了,那之后的改变都不可见:
slider.minimumValue=0.0;
slider.maximumValue=2.0;
slider.value=1.0;
//scale,出现0值需特殊处理
if(slider.value<0.001){
layer.hidden=YES;
return;
}else{
layer.hidden=NO;
}
layer.transform = CATransform3DIdentity;
[layer setValue:[NSNumber numberWithFloat:slider.value] forKeyPath:@"transform.scale"];
(3)transform.rotation是默认改变的z,而不是三个坐标一起变
(4)transform.translation是改变位置,x为正向右移,y为正向下移(和二维坐标一致),二维时z无变化
修正:并非无变化(google:iphone transform.translation.z
找到http://stackoverflow.com/questions/4150105/my-calayer-is-not-appearing 有一句有用:.m34 is for z-axis transforms)
这样的话,加入下面这句就可以改变Z坐标:
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / -100;
layer.transform = transform;
加上setValue,Z改变量随m34的值变化而不同,暂时不知道m34和translation.z的关系…
[layer setValue:[NSNumber numberWithFloat:slider.value] forKeyPath:@"transform.translation.z"];