简体   繁体   中英

-(void) drawRect:(CGRect)rect; is using up nearly all of iPhone CPU

- (void)drawRect:(CGRect)rect{

    float sliceSize = rect.size.width / imagesShownAtOnce;
    //Apply our clipping region and fill it with black
    [clippingRegion addClip];
    [clippingRegion fill];

    //Draw the 3 images (+1 for inbetween), with our scroll amount.
    CGPoint loc;
    for (int i=0;i<imagesShownAtOnce+1;i++){
        loc = CGPointMake(rect.origin.x+(i*sliceSize)-imageScroll, rect.origin.y);
        [[buttonImages objectAtIndex:i] drawAtPoint:loc];
    }

    //Draw the text region background
    [[UIColor blackColor] setFill];
    [textRegion fillWithBlendMode:kCGBlendModeNormal alpha:0.4f];

     //Draw the actual text.
    CGRect textRectangle = CGRectMake(rect.origin.x+16,rect.origin.y+rect.size.height*4/5.6,rect.size.width/1.5,rect.size.height/3);
    [[UIColor whiteColor] setFill];
    [buttonText drawInRect:textRectangle withFont:[UIFont fontWithName:@"Avenir-HeavyOblique" size:22]];
}

clippingRegion and textRegion are UIBezierPaths to give me the rounded rectangles I want (First for a clipping region, 2nd as an overlay for my text)

The middle section is drawing 3 images and letting them scroll along, which im updating every 2 refreshes from a CADisplayLink , and that invalidates the draw region by calling [self setNeedsDisplay] , and also increasing my imageScroll variable.


Now that that background information is done, here is my issue:

It runs, and even runs smoothly. But it is using up an absolutely high amount of CPU time (80%+)!! How do I push this off to the GPU on the phone instead? Someone told me about CALayers but I've never dealt with them before

Draw each component of your drawing once into something (a view or layer) and let it hold the cached the drawing. Then you just move or transform each component, and exactly as you say, it's all done by the GPU.

You could do this with individual views or with individual layers, but that doesn't really matter (a view is a layer, under the hood). The point is that there is no need to be constantly redrawing from scratch when all you really want is to move the same persistent pieces around.

Learning about CALayer would be a good idea, as it is in fact the basis of all drawing on iOS. What could be more important to know about than that?

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