您可以为此使用CALayer:它比UIImageView 更轻量级,并且使用起来非常简单。这个想法是基于来自this post 的示例,并且是从一个工作项目中提取出来的。
// "sprites.png" is a 192x128 picture containing two rows of three 64x64 sprites each
NSString *path = [[NSBundle mainBundle] pathForResource:@"sprites.png" ofType:nil];
CGImageRef img = [UIImage imageWithContentsOfFile:path].CGImage;
imgLayer = [CALayer layer];
imgLayer.contents = (__bridge id)img;
// Frame defines the position of your sprite inside your view
imgLayer.frame = CGRectMake(horOffset, verOffset, 64, 64);
imgLayer.bounds = CGRectMake(0, 0, 64, 64); // The size of an individual sprite
// Pick the sprite from the top row, left column
imgLayer.contentsRect = CGRectMake(0, 0, 1.0/3.0, 1.0/2.0);
// Top row, middle column
// imgLayer.contentsRect = CGRectMake(1.0/3, 0, 1.0/3.0, 1.0/2.0);
// Top row, right column
// imgLayer.contentsRect = CGRectMake(2.0/3, 0, 1.0/3.0, 1.0/2.0);
// Bottom row, left column
// imgLayer.contentsRect = CGRectMake(0, 1.0/2, 1.0/3.0, 1.0/2.0);
// Bottom row, middle column
// imgLayer.contentsRect = CGRectMake(1.0/3, 1.0/2, 1.0/3.0, 1.0/2.0);
// Bottom row, right column
// imgLayer.contentsRect = CGRectMake(2.0/3, 1.0/2, 1.0/3.0, 1.0/2.0);
[self.layer addSublayer:imgLayer];