该层应该放在哪里?
我们画个图:
我们可以更进一步做一些三角函数,但我们就到此为止吧。很明显,横幅的中上点应该位于(20,20)
。我们可以告诉 Core Animation 这样做。
定位图层
将其视为四个单独的步骤:
- 设置图层大小
- 确定图层中的哪个点是方便的参考点
- 设置该参考点的位置
- 围绕参考点旋转图层
这些对应于四个属性:bounds
, anchorPoint
, position
, and transform
.
你不想触碰frame
属性,因为它的值是源自 the bounds
, position
, transform
, and anchorPoint
。如果您尝试设置frame
, CALayer 将尝试反转transform
,将其应用于您给出的矩形,然后设置bounds
and position
。这可能不会给出你想要的结果,所以你最好完全忽略它——这样就不会那么混乱了。
(有关更多信息,请参阅核心动画指南 http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40004514,特别是该部分图层对象定义自己的几何形状 http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide/CoreAnimationBasics/CoreAnimationBasics.html#//apple_ref/doc/uid/TP40004514-CH2-SW15.)
在代码中,我们将:
- Set
bounds
到直角0, 0, width, height
。 (我是故意离开的width
对你来说——它必须大于 56。)
- Set
anchorPoint
说到点子上0.5, 0
。换句话说,位于层宽度的中间、层的顶部。
- Set
position
说到点子上20, 20
.
- Set
transform
旋转 45°。
顺便说一下,在下面的代码中,我设置了affineTransform
而不是transform
,只是因为它对于简单的二维转换稍微方便一些。
何时设置图层
你是对的-drawRect:
是创建和添加图层的错误位置。该方法应该绘制到视图的内容中(其CGContext
)但是做nothing else.
layoutSubviews
会起作用,但它的调用频率会比您预期的要高,并且您不想每次都创建和添加新层。
看起来你只需要设置一次图层的几何形状,就再也不用碰它了。为什么不直接创建或销毁图层hasBanner
属性改变了?
@interface MyTableViewCell ()
@property (nonatomic) BOOL hasLayer;
@property (nonatomic) CALayer* bannerLayer;
@end
- (void)setHasBanner:(BOOL)hasBanner
{
if (hasBanner != _hasBanner) {
_hasBanner = hasBanner;
if (hasBanner) {
CALayer* banner = [CALayer layer];
banner.backgroundColor = [UIColor colorWithRed:.5f green:.5f blue:.5f alpha:1.f].CGColor;
banner.bounds = CGRectMake(0, 0, 56, 15);
banner.anchorPoint = CGPointMake(0.5, 0);
banner.position = CGPointMake(20, 20);
banner.affineTransform = CGAffineTransformMakeRotation(-45.0 / 180.0 * M_PI);
// Add the layer to the view, and remember it for later
[self.layer addSublayer:banner];
self.bannerLayer = banner;
} else {
// Remove the layer from the view, and discard it
[self.bannerLayer removeFromSuperlayer];
self.bannerLayer = nil;
}
}
}