0

我有一个 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

    }
}
4

1 回答 1

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

于 2009-09-06T15:58:01.703 回答