我是初学者,我正在做一些练习以熟悉CALayer ......
我只是想知道如何“倾斜”(或倾斜)CALayer 45°角?
谢谢。
答案 0 :(得分:12)
CALayers拥有一个affineTransform
的属性CGAffineTransform CGAffineTransformMakeSkew(CGFloat skewAmount)
{
CGAffineTransform skewTransform = CGAffineTransformIdentity;
skewTransform.b = skewAmount;
return skewTransform;
}
。该文件明确指出:
缩放,旋转和翻译 最常用的操作 由仿射变换支持,但是 倾斜也是可能的。
(显然强调我的)
没有内置帮助器来构造偏斜变换,但你可以做一些像(未经测试的):
layer.affineTransform = CGAffineTransformMakeSkew(1.0f);
然后,对于倾斜,使垂直的东西与水平方向成45度,你会使用:
{{1}}
答案 1 :(得分:8)
可以使用矩阵运算转换CALayers。偏斜变换由以下矩阵
表示
因此,如果您想沿x轴进行倾斜变换,可以使用以下示例。
CALayer* layer = [CALayer layer];
layer.frame = CGRectMake(50,50,50,50);
layer.backgroundColor = [UIColor blueColor].CGColor;
[self.window.layer addSublayer:layer];
float theta = -45.0f;
CGAffineTransform t = CGAffineTransformIdentity;
t.b = tan(theta*M_PI/180.0f);
layer.transform = CATransform3DMakeAffineTransform(t);
以下示例将生成一个类似于以下内容的图层
答案 2 :(得分:7)
你可以这样做但你必须弄乱layer
的{{1}}属性,这是一个transform
。你将不得不做一些矢量数学来做这件事。有关详细信息,请参阅this answer中的struct CATransform3D
功能。
你会想做这样的事情:
compute_transform_matrix(...)
检查我的数学。应该是对的。
答案 3 :(得分:0)
There are a lot of resources on how transforms work and it takes a bit of time to really understand them (at least for me!), here is some straight-to-the-point code that makes sure to indicate to which axis the transform is applied.
/*!
* Positive `skewX` creates a shift to the left.
* Negative `skewX` creates a shift to the right.
*
* `skewX` is NOT pixel based. Test values of 0.0f - 1.0f.
*/
CGAffineTransform CGAffineTransformMakeSkewX(CGFloat skewX)
{
return CGAffineTransformMakeSkew(skewX, 0.0f);
}
/*!
* Positive `skewY` creates a shift to the bottom.
* Negative `skewY` creates a shift to the top.
*
* `skewY` is NOT pixel based. Test values of 0.0f - 1.0f.
*/
CGAffineTransform CGAffineTransformMakeSkewY(CGFloat skewY)
{
return CGAffineTransformMakeSkew(0.0f, skewY);
}
/*!
* Positive `skewX` creates a shift to the left.
* Negative `skewX` creates a shift to the right.
*
* Positive `skewY` creates a shift to the bottom.
* Negative `skewY` creates a shift to the top.
*
* The skew values are NOT pixel based. Test values of 0.0f - 1.0f.
*/
CGAffineTransform CGAffineTransformMakeSkew(CGFloat skewX, CGFloat skewY)
{
return CGAffineTransformMake(1.0f, skewY, skewX, 1.0f, 0.0f, 0.0f);
}