图片浏览与Tom猫动画实现
图像变换与按钮交互
通过修改按钮的transform属性实现图像的动态效果。
缩放操作
- (IBAction)scaleButton:(UIButton *)btn {
CGRect frame = self.imageView.frame;
CGFloat factor = btn.isSelected ? 1.2f : 0.8f;
frame.size.width *= factor;
frame.size.height *= factor;
[UIView animateWithDuration:0.5 animations:^{
self.imageView.frame = frame;
}];
}
位移变换
CGAffineTransform move = CGAffineTransformTranslate(self.imageView.transform, 0, -30);
self.imageView.transform = move;
NSLog(@"%@", NSStringFromCGAffineTransform(self.imageView.transform));
旋转效果
CGFloat rotation = btn.isSelected ? -M_PI_4 : M_PI_4;
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, rotation);
动态按钮创建
- (void)viewDidLoad {
[super viewDidLoad];
// 创建系统按钮
UIButton *sysBtn = [UIButton buttonWithType:UIButtonTypeSystem];
sysBtn.frame = CGRectMake(20, 20, 100, 40);
[sysBtn setTitle:@"点击" forState:UIControlStateNormal];
[self.view addSubview:sysBtn];
// 创建自定义按钮
UIButton *customBtn = [[UIButton alloc] initWithFrame:CGRectMake(150, 20, 100, 40)];
customBtn.backgroundColor = [UIColor lightGrayColor];
[customBtn setBackgroundImage:[UIImage imageNamed:@"btn_normal"] forState:UIControlStateNormal];
[customBtn setBackgroundImage:[UIImage imageNamed:@"btn_pressed"] forState:UIControlStateHighlighted];
[self.view addSubview:customBtn];
}
图像切换界面
实现左右按钮控制图片浏览功能。
- (NSArray *)imageData {
if (!_imageData) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Gallery" ofType:@"plist"];
_imageData = [NSArray arrayWithContentsOfFile:path];
}
return _imageData;
}
- (void)updateDisplay {
NSDictionary *item = self.imageData[self.currentIndex];
self.imageView.image = [UIImage imageNamed:item[@"imageName"]];
self.titleLabel.text = item[@"description"];
self.leftBtn.enabled = self.currentIndex > 0;
self.rightBtn.enabled = self.currentIndex < self.imageData.count - 1;
}
内存管理实践
强引用与弱引用的区别:
- 强引用:__strong Person *person = [[Person alloc] init];
- 弱引用:__weak Person *weakSelf = person;
自动释放机制确保无强引用对象被回收。
Tom猫动画实现
- (IBAction)playAnimation:(UIButton *)sender {
if (self.catImageView.isAnimating) return;
NSMutableArray *frames = [NSMutableArray array];
for (int i = 0; i < 25; i++) {
NSString *filename = [NSString stringWithFormat:@"cat_%02d.jpg", i];
NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:nil];
[frames addObject:[UIImage imageWithContentsOfFile:path]];
}
self.catImageView.animationImages = frames;
self.catImageView.animationDuration = 2.0;
[self.catImageView startAnimating];
[self performSelector:@selector(clearAnimation) withObject:nil afterDelay:self.catImageView.animationDuration];
}
- (void)clearAnimation {
self.catImageView.animationImages = nil;
}