减少内存占用
- 优化图片资源:
- 措施:使用合适的图片格式(如WebP在支持的情况下,iOS 14+支持),根据不同设备分辨率加载合适尺寸的图片。避免在内存中同时加载过大尺寸图片。
- 示例代码:
// 使用ImageIO框架根据设备分辨率加载合适图片
CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)imageURL, NULL);
CFDictionaryRef options = (__bridge CFDictionaryRef)@{
(id)kCGImageSourceCreateThumbnailFromImageAlways: (id)kCFBooleanTrue,
(id)kCGImageSourceThumbnailMaxPixelSize: @(UIScreen.mainScreen.scale * 100) // 根据需要调整尺寸
};
CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, options);
UIImage *image = [UIImage imageWithCGImage:thumbnail];
CFRelease(thumbnail);
CFRelease(source);
- 避免不必要的对象创建:
- 措施:复用对象,如使用对象池。对于动画过程中频繁使用的小对象(如
CGPoint
、CGRect
等结构体),尽量在栈上创建而不是堆上创建对象。
- 示例代码:
// 复用UIView动画相关对象
static CADisplayLink *displayLink;
if (!displayLink) {
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(animateView)];
[displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
提高动画流畅度
- 使用正确的动画方式:
- 措施:对于简单动画,使用
UIView
的动画块(animateWithDuration:animations:
等方法),因为它对性能进行了优化。对于复杂动画,使用 Core Animation
并利用 CADisplayLink
来控制动画节奏。尽量避免在主线程进行大量计算的同时执行动画。
- 示例代码(UIView动画):
[UIView animateWithDuration:0.3 animations:^{
view.alpha = 0.5;
view.transform = CGAffineTransformMakeScale(1.2, 1.2);
}];
- **示例代码(Core Animation + CADisplayLink)**:
// 创建一个CALayer动画
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
animation.fromValue = @(view.layer.position.x);
animation.toValue = @(view.layer.position.x + 200);
animation.duration = 1;
animation.repeatCount = HUGE_VALF;
[view.layer addAnimation:animation forKey:@"positionAnimation"];
// 使用CADisplayLink控制动画
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateAnimation)];
[displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
- 优化渲染:
- 措施:减少视图层级的复杂度,避免过度绘制。使用
shouldRasterize
属性将复杂视图缓存为位图,但要注意其适用场景,因为缓存可能占用额外内存。
- 示例代码:
// 设置视图进行光栅化
view.layer.shouldRasterize = YES;
view.layer.rasterizationScale = [UIScreen mainScreen].scale;
- 硬件加速:
- 措施:利用
CAEAGLLayer
进行基于OpenGL ES的自定义渲染,将渲染操作交给GPU处理,以提高性能。
- 示例代码(简单的OpenGL ES初始化):
CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.view.layer;
eaglLayer.drawableProperties = @{kEAGLDrawablePropertyRetainedBacking: @NO, kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8};
_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
if (!_context) {
NSLog(@"Failed to create ES context");
return;
}
if (![EAGLContext setCurrentContext:_context]) {
NSLog(@"Failed to set ES context current");
return;
}