//实现原理是用layer.contensRect实现的,参考文献:http://blog.csdn.net/mamong/article/details/8534999
CGFloat ratio = 0.1;
for (int i = 0; i < 100; i++) {
UIImageView imageView = [[UIImageView alloc] init];
imageView.backgroundColor = [UIColor redColor];
imageView.image = image;
NSInteger column = i % 10; // 列
NSInteger row = i / 10; // 行
//层内容的可视区域
imageView.layer.contentsRect = CGRectMake(ratiocolumn, rowratio, ratio, ratio);
imageView.frame = CGRectMake(self.frame.size.widthratiocolumn, row(self.frame.size.heightratio), self.frame.size.widthratio, self.frame.size.height*ratio);
[self addSubview:imageView];//将控件添加到self
}
//然后用UIView animateWithDuration动画改变所有self的所有子控件layer.transform属性就可以实现打碎效果,还原也一样的原理
// 打碎
-(void)smash {
[UIView animateWithDuration:1 animations:^{
[self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOLBOOL * _Nonnull stop) {
UIImageView *imageView = obj;
imageView.layer.transform = [self configTransform3DWithRotateAngle:[self getRandomNumber:0 to:360] andPositionX:[self getRandomNumber:0 to:100] andPositionY:[self getRandomNumber:0 to:100]];
}];
}];
}
//该方法是传一个角度,x,y值进来 returny一个CATransform3D类型的对象
- (CATransform3D)configTransform3DWithRotateAngle:(double)angle andPositionX:(double)x andPositionY:(double)y
{
CATransform3D transform = CATransform3DIdentity;
// iOS的三维透视投影 实现view(layer)的透视效果(就是近大远小),是通过设置m34的参考:http://blog.csdn.net/dreamjuvenile/article/details/51898444
// transform.m34 = 1/0;
/*
旋转 CATransform3DRotate (CATransform3D t, CGFloat angle,CGFloat x, CGFloat y, CGFloat z) angle旋转弧度:角度 * M_PI / 180,
x值范围-1 --- 1之间 正数表示左侧看向外旋转,负数表示向里CATransform3DRotate(transform, M_PIangle/180, 1, 0, 0)
y值范围-1 --- 1之间 正数左侧看表示向外旋转,负数表示向里CATransform3DRotate(transform, M_PIangle/180, 0, 1, 0)
同时设置x,y表示沿着对角线翻转
CATransform3DRotate(transform, M_PIangle/180, 1, 1, 0)
z值范围-1 --- 1之间 正数逆时针旋转,负数表示顺CATransform3DRotate(transform, M_PIangle/180, 0, 0, -1)
同时设置x,y,z按照设定的数值进行旋转
CATransform3D rotateTransform = CATransform3DRotate(transform, M_PI*angle/180, 1, 1, 1);
/
CATransform3D rotateTransform = CATransform3DRotate(transform, M_PIangle/180, 1, 1, 1);
// 移动
CATransform3D moveanim = CATransform3DMakeTranslation(x, y, 0);
// 合并
CATransform3D concatTransform = CATransform3DConcat(rotateTransform, moveanim);
return concatTransform;
}
//传入两个int数据类型生成一个范围的随机数
-(CGFloat)getRandomNumber:(int)from to:(int)to
{
return (from+ 1 + (arc4random() % (to - from + 1)));
}
源代码地址:https://github.com/PanDongGG/smashImageView