简体   繁体   中英

Which way is better to move an ImageView

I would like to move an ImageView around the screen many times, until now I have found two ways. However I am not sure which one is more efficient, or maybe both are the same. Please, could I have some advice ? Thanks.

// Create ImageView and add subview
UIImageView imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
imgView.frame = CGRectMake(0, 0, image_width, image_height);
[[self view] addSubview:imgView];   
[imgView release];

// New Coordinates
int xNew = 100;
int yNew = 130;

// First way to move ImageView:
imgView.frame = CGRectMake(xNew, yNew, image_width, image_height);

// Second way to move ImageView:
CGPoint center;
center.x = xNew;
center.y = yNew;
imgView.center = center;

You could also use CGAffineTransformTranslate, like so:

imgView.transform = CGAffineTransformIdentity;
imgView.transform = CGAffineTransformTranslate(imgView.transform, 0, -70);
imgView.frame = CGRectMake(xNew, yNew, image_width, image_height);

imgView.center = CGPointMake(xNew, yNew);

Actually this is more of the comparison.

If you need to ever resize the object or want to give coords from the upper left I would go with the first if you just need to move it and are comfortable giving centered cords it would seem more logical to go with the second method.

Technically, the second way is a tiny bit faster because you don't touch image views' bounds, which in theory might be expensive, depending on Apple's implementation. But in the second way a view's frame may fall outside pixel boundaries (Retina displays rule, don't they?) which may result in blurry images.

Note, however, that the results will be different because in the first case (xNew, yNew) is an upper left corner of a view, while in the second one (xNew, yNew) is a view's center.

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