2009-09-05 62 views
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 

    } 
} 

回答

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