|
一直以来想着,整理一下学习iOS开发的经历.借着这段空闲的时间,特意为想入门iOS开发,或者刚入门的新手,提供一些练手的小项目.
Tom猫游戏,想必大家都很熟悉,各种版本的Tom猫.别看着这样一个小小的游戏,想要把它做成比较完美的项目,必须要多思考.比如说:1.界面的合理搭建;2.代码的封装性;3.CPU利用率;4.内存的优化.
根据以上的几个侧重点,重写了Tom猫这个小项目,希望能对新手们有所帮助.大神们么井喷,本人实属入门级别而已.
(1)延时加载技术,也叫懒加载.提高CPU的利用率,加快启动速度.
- - (NSDictionary *)imgs{
- if (!_imgs) {
- NSString *path = [[NSBundle mainBundle] pathForResource:@"tom.plist" ofType:nil];
- NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
- _imgs = dict;
- }
- return _imgs;
- }
复制代码 (2)代码的封装:注意设置控件的tag值时,最后使用100以后的值,避免与Xcode内部系统产生冲突.
(3)设置序列帧动画效果:注意图片无缓存加载方式,以及图片对象数组的及时释放.
- - (void)playAnimationWithCount:(int)count andPrefixName:(NSString *)name{
- if(self.imgView.isAnimating){
- return;
- }
- NSMutableArray *imgArray = [NSMutableArray array];
- for (int i = 0; i < count; i++) {
- NSString *imgName = [NSString stringWithFormat:@"%@_%02d.jpg",name,i];
- NSString *imgPath = [[NSBundle mainBundle] pathForResource:imgName ofType:nil];
- UIImage *image = [UIImage imageWithContentsOfFile:imgPath];
- UIImage *newImage = [self getImage:image andSize:[UIScreen mainScreen].bounds.size];
- [imgArray addObject:newImage];
- }
- self.imgView.animationImages = imgArray;
- self.imgView.animationDuration = count * 0.1;
- self.imgView.animationRepeatCount = 1;
- [self.imgView startAnimating];
- //必须把创建的数组,在播放动画完成后,置为nil,进行释放.
- [self.imgView performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:count * 0.1];
- }
复制代码 (4)开辟子线程对图片进行重采集工作,减轻主线程的任务,加快速度,以及优化内存.
- - (UIImage *)getImage:(UIImage *)image andSize:(CGSize)size{
- UIGraphicsBeginImageContext(size);
- CGRect imageRect = CGRectMake(0, 0, size.width, size.height);
- [image drawInRect:imageRect];
- UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return newImage;
- }
复制代码 预览Tom猫项目的效果:
总结:每写一个新的项目,或者老项目,其实知识点都是在逐渐累加的过程.新的方法,新的技术,新的优化效果等等,都是在实践操作,查资料,看博客等中获取到的.编程之路,就是一条学习之路.
源码下载地址:
|
|