简体   繁体   中英

setNeedsDisplay confusion

I'm using this to move my image:

meteorDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(moveImage:)];

Here is my moveImage: method:

-(void) moveImage:(CADisplayLink *)sender{
    CGPoint img;
    imgLocation = imgImageView.center;
    if (img < 100) {
        img.y++;
    }
    else{
         imgLocation.y = 0;
    }
    imgImageView.center = imgLocation;    
}

This updates the location of my image on screen no matter what. Why does setNeedsDisplay have no effect here? What is the point of setNeedsDisplay ?

I assume imgImageView is an instance of UIImageView . If it's not an instance of UIImageView , edit your question to tell us what it is.

Changing the center property of a view never requires your app to redraw the view. The display server (which is a separate process named backboardd in iOS 6 and springboard in earlier versions) has a copy of your view's pixel data already. When you change a view's center , the view just informs the display server of its new position, and the display server copies the view's pixel data to the appropriate parts of the screen.

Thus changing the center property of a view never requires you to send setNeedsDisplay .

More specifically, UIImageView doesn't even implement drawRect: . Instead, UIImageView just sends its image's pixel data to the display server when you set its image. So even if you send setNeedsDisplay to a UIImageView , it still won't run any drawRect: method.

By the way, you can do this in your own UIView subclasses too, by setting self.layer.contents to a CGImageRef instead of implementing drawRect: . You will need to #import <QuartzCore/QuartzCore.h> to do this. Of course, UIImageView does other things too, like handling animated and resizable images.

When you set properties that affect the layout of an object, setNeedsDisplay will be called internally. You need to call it yourself for custom properties, etc, that don't automatically call it.

setNeedsDisplay only applies to the contents of a layer or view. Ie, if the contents of a view has changed and needs to be redrawn, you would use setNeedsDisplay to tell the view that it needs to be redrawn and that would trigger its drawRect method.

Transformations on a view, such as position, scale, and rotation, etc., are handled directly by the GPU and do not require the view to be redrawn; therefore, setNeedsDisplay does not apply when you're simply moving or transforming a view.

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