//實現(xiàn)原理是用layer.contensRect實現(xiàn)的走越,參考文獻: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; // 行
//層內(nèi)容的可視區(qū)域
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屬性就可以實現(xiàn)打碎效果趣倾,還原也一樣的原理
// 打碎
-(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的三維透視投影 實現(xiàn)view(layer)的透視效果(就是近大遠小)啼染,是通過設(shè)置m34的參考:http://blog.csdn.net/dreamjuvenile/article/details/51898444
// transform.m34 = 1/0;
/*
旋轉(zhuǎn) CATransform3DRotate (CATransform3D t, CGFloat angle,CGFloat x, CGFloat y, CGFloat z) angle旋轉(zhuǎn)弧度:角度 * M_PI / 180座柱,
x值范圍-1 --- 1之間 正數(shù)表示左側(cè)看向外旋轉(zhuǎn),負數(shù)表示向里CATransform3DRotate(transform, M_PIangle/180, 1, 0, 0)
y值范圍-1 --- 1之間 正數(shù)左側(cè)看表示向外旋轉(zhuǎn)输吏,負數(shù)表示向里CATransform3DRotate(transform, M_PIangle/180, 0, 1, 0)
同時設(shè)置x权旷,y表示沿著對角線翻轉(zhuǎn)
CATransform3DRotate(transform, M_PIangle/180, 1, 1, 0)
z值范圍-1 --- 1之間 正數(shù)逆時針旋轉(zhuǎn),負數(shù)表示順CATransform3DRotate(transform, M_PIangle/180, 0, 0, -1)
同時設(shè)置x,y,z按照設(shè)定的數(shù)值進行旋轉(zhuǎn)
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數(shù)據(jù)類型生成一個范圍的隨機數(shù)
-(CGFloat)getRandomNumber:(int)from to:(int)to
{
return (from+ 1 + (arc4random() % (to - from + 1)));
}
源代碼地址:https://github.com/PanDongGG/smashImageView