原文地址:http://superman474.blog.163.com/blog/static/120661462011857559881/
提供layer内容
1.提供CALayer内容
(1)设置contents属性
CALayer *theLayer; |
|
// create the layer and set the bounds and position |
theLayer=[CALayer layer]; |
theLayer.position=CGPointMake(50.0f,50.0f); |
theLayer.bounds=CGRectMake(0.0f,0.0f,100.0f,100.0f); |
|
// set the contents property to a CGImageRef |
// specified by theImage (loaded elsewhere) |
theLayer.contents=theImage; |
(2)使用代理去提供内容
- (void)displayLayer:(CALayer *)theLayer |
{ |
// check the value of the layer's state key |
if ([[theLayer valueForKey:@"state"] boolValue]) |
{ |
// display the yes image |
theLayer.contents=[someHelperObject loadStateYesImage]; |
} |
else { |
// display the no image |
theLayer.contents=[someHelperObject loadStateNoImage]; |
} |
} |
drawLayer:inContext:
下面就是一个代理实现了drawLayer:inContext:的方法:
- (void)drawLayer:(CALayer *)theLayer |
inContext:(CGContextRef)theContext |
{ |
CGMutablePathRef thePath = CGPathCreateMutable(); |
|
CGPathMoveToPoint(thePath,NULL,15.0f,15.f); |
CGPathAddCurveToPoint(thePath, |
NULL, |
15.f,250.0f, |
295.0f,250.0f, |
295.0f,15.0f); |
|
CGContextBeginPath(theContext); |
CGContextAddPath(theContext, thePath ); |
|
CGContextSetLineWidth(theContext, |
[[theLayer valueForKey:@"lineWidth"] floatValue]); |
CGContextStrokePath(theContext); |
|
// release the path |
CFRelease(thePath); |
} |
- (void)display |
{ |
// check the value of the layer's state key |
if (self.state) |
{ |
// display the yes image |
self.contents=[someHelperObject loadStateYesImage]; |
} |
else { |
// display the no image |
self.contents=[someHelperObject loadStateNoImage]; |
} |
} |
- (void)drawInContext:(CGContextRef)theContext |
{ |
CGMutablePathRef thePath = CGPathCreateMutable(); |
|
CGPathMoveToPoint(thePath,NULL,15.0f,15.f); |
CGPathAddCurveToPoint(thePath, |
NULL, |
15.f,250.0f, |
295.0f,250.0f, |
295.0f,15.0f); |
|
CGContextBeginPath(theContext); |
CGContextAddPath(theContext, thePath ); |
|
CGContextSetLineWidth(theContext, |
self.lineWidth); |
CGContextSetStrokeColorW |
self.lineColor); |
CGContextStrokePath(theContext); |
CFRelease(thePath); |
} |
2.positioning layer的content。
CALayer提供一个属性contentsGravity允许我们去position and scale layer的contents image。缺省情况下,content image填充整个layer bounds。忽视自然的图像纵横比。
使用contentsGravity positioning常量去具体image的位置,如下图:
当使用positioning 常量时,contentsCenter属性将不在使用。
contentsGravity属性可以被设置为下面三种来控制其sacle。设置成下列三种时,上面的9种就失效。