简体   繁体   中英

CALayer draw outside of rect

I'm using this code to add a layer to a custom UIView and it works like a charm:

 CGRect newrect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    CALayer* heartBackground = [CALayer layer];
    heartBackground.contents = (__bridge id)([UIImage imageNamed:@"5HeartsGray"].CGImage);
    heartBackground.frame = newrect;
    [self.layer addSublayer:heartBackground];

But when I tried to use it in draw method using Quartz using a new Rect(like this)

        CGContextSaveGState(context);
    CGRect ratingRect = CGRectMake(250, 100, 150, 20);

    CALayer* heartBackground = [CALayer layer];
    heartBackground.contents = (__bridge id)([UIImage imageNamed:@"5HeartsGray"].CGImage);
    heartBackground.frame = ratingRect;
    [heartBackground renderInContext:context];
    CGContextRestoreGState(context);

It renders in the beginning of the frame and not inside of ratingRect.

If I call [heartBackground setNeedsDisplay] it disappear. The same thing with heartBackground.masksToBounds = YES

What I'm doing wrong. Do I need To switch to CGLayer because I'm using CoreGraphics?

This is the output when working with CoreGraphics (as you see the hearts starts at coordinates x=0, y=0 and normally it starts at x=250, y=100): 在此处输入图片说明

It doesn't make sense to create and draw a CALayer inside draw function of a UIView . CALayer is an independently drawable unit and it draws itself on its parentLayer's context by default. Which means if you really want to use separate CALayers try adding as many subLayers to self.layer (inside a UIView ) as you want, set their frames and they'll get drawn when their container view shows up. Regarding your problem, here's what you can try.

Option 1: Take this code

CGRect ratingRect = CGRectMake(250, 100, 150, 20);
CALayer* heartBackground = [CALayer layer];
heartBackground.contents = (__bridge id)([UIImage imageNamed:@"5HeartsGray"].CGImage);
heartBackground.frame = ratingRect;
[self.layer addSubLayer:heartBackground];

Out of the drawRect: method and write it in initWithFrame: and in drawRect simply do [heartBackground renderInContext:UIGraphicsGetCurrentContext];

Option 2: Draw your hearts without a CALayer.

CGRect ratingRect = CGRectMake(250, 100, 150, 20);
[[UIImage imageNamed:@"5HeartsGray"] drawInRect:ratingRect];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM