Graphics Reference
In-Depth Information
//create layer
CALayer *layer = [ CALayer layer ];
layer. frame = CGRectMake ( 0 , 0 , SIZE , SIZE );
layer. position = CGPointMake (x* SPACING , y* SPACING );
layer. zPosition = -z* SPACING ;
//set background color
layer. backgroundColor =
[ UIColor colorWithWhite : 1 -z*( 1.0 / DEPTH ) alpha : 1 ]. CGColor ;
//attach to scroll view
[visibleLayers addObject :layer];
}
}
}
//update layers
self . scrollView . layer . sublayers = visibleLayers;
//log
NSLog ( @"displayed: %i/%i" , [visibleLayers count ], DEPTH * HEIGHT * WIDTH );
}
@end
The mathematics of the calculation used here are very specific to this particular problem,
but the principle is applicable to other situations, as well. (When you use a UITableView or
UICollectionView , it does something similar behind the scenes to work out which of the
cells need to be displayed.) The result is that our app can now handle hundreds of thousands
of “virtual” layers without any performance problems because it doesn't ever need to
instantiate more than a few hundred of them at a time.
Object Recycling
Another trick that we can use when managing a large number of similar views or layers is
to recycle them. Object recycling is quite a common pattern in iOS; it's used for
UITableView and UICollectionView cells, and for the annotation pins in MKMapView ,
along with many other examples.
The basic principle of object recycling is that you create a pool of identical objects. When
you finish with a particular instance of an object (a layer in this case), you add it to the
object pool. Each time you need an instance, you take one out of the pool. Only if the pool
is empty do you create a new one.
Search WWH ::




Custom Search