我有一个UIView子类,它实例化了它的三个兄弟子层。其中两个子图层的内容设置为图像文件;第三个是在
中绘制的图形- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
方法。问题是我的绘图层总是出现在图像层后面。我尝试重新排序子图层数组并改变子图层的zPosition属性无济于事。我错过了什么?
- (void)setupLayers
{
CALayer *rootLayer = [self layer];
_meterLayer = [CALayer layer];
[_meterLayer setContents:(id)[[UIImage imageNamed:@"HealthMeterRadial60x60.png"] CGImage]];
_pointerLayer = [CALayer layer];
[_pointerLayer setContents:(id)[[UIImage imageNamed:@"HealthMeterRadialPointer60x60.png"] CGImage]];
_labelLayer = [CALayer layer];
[self set_labelText:@"Health"];
[rootLayer addSublayer:_meterLayer];
[rootLayer insertSublayer:_pointerLayer above:_meterLayer];
[rootLayer insertSublayer:_labelLayer above:_pointerLayer];
}
drawLayerInContext方法:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
if( layer = _labelLayer) {
//draw graphics ... omitted for clarity; works, but always behind images
}
}
答案 0 :(得分:2)
问题的解决方案是将_labelLayer的内容绘制到图像上下文中,并将其内容属性设置为生成的CGImage。设置图层时:
// create a layer for the name of the meter
_labelLayer = [CALayer layer];
[_labelLayer setFrame:CGRectMake(0, 0, rootLayer.frame.size.width, rootLayer.frame.size.height)];
[self set_labelText:@"Health"];
[_labelLayer setContents:(id)[[self labelImageContent] CGImage]];
然后将内容绘制到CGImage:
- (UIImage *)labelImageContent {
NSAssert( _labelText != nil, @"No label set for radial meter");
// get a frame for our layer and start a context to make an image
CGRect rect = _labelLayer.frame;
UIGraphicsBeginImageContext(rect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// measure the size of our text first to know where to position
CGSize textsize = [_labelText sizeWithFont:[UIFont systemFontOfSize:10]];
const char *text = [_labelText cStringUsingEncoding:NSUTF8StringEncoding];
size_t textlen = strlen(text);
// this is just a testing rectangle
CGContextSetRGBFillColor(ctx, 1, 0, 0, 0.5);
CGContextFillRect(ctx,rect);
/* save our context before writing text */
CGContextSaveGState(ctx);
CGContextSelectFont(ctx, "Helvetica", 9, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(ctx, kCGTextFill);
/* this will flip our text so that it is readable */
CGAffineTransform flipTransform = CGAffineTransformMakeTranslation(0.0f, rect.size.height);
flipTransform = CGAffineTransformScale(flipTransform, 1.0f, -1.0f);
// write our title in black
float opaqueBlack[] = {0,0,0,1};
CGContextSetFillColor(ctx, opaqueBlack);
CGContextConcatCTM(ctx, flipTransform);
CGContextShowTextAtPoint(ctx, rect.origin.x + 0.5*(60-textsize.width), rect.origin.y + 40 - 0.5 * textsize.height - 5, text, textlen);
/* get our graphics state back */
CGContextRestoreGState(ctx);
UIImage *labelPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return labelPic;
}
DF