IOS 圖片摺疊效果實現
當手指在圖片中上下滑動的時候,圖片的上半部分會有摺疊效果。類似地可以擴充套件到其他需要摺疊的場景中。
layer.contentsRect
用來擷取layer的部分內容重新在frame中渲染。程式碼及關鍵註釋如下:
@interface ViewController ()
{
/**
* 建立兩個UIImageView,分別用來儲存圖片的上、下兩部分。
*/
UIImageView *imageViewUp;
UIImageView *imageViewDown;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor = [UIColorwhiteColor];
// Do any additional setup after loading the view, typically from a nib.
imageViewUp = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"1"]];
//設定摺疊的錨點
imageViewUp.layer.anchorPoint = CGPointMake(
imageViewUp.frame = CGRectMake(10, 100, 300, 150);
//設定imageView的內容為圖片的上半部分
imageViewUp.layer.contentsRect = CGRectMake(0, 0, 1, 0.5);
[self.viewaddSubview:imageViewUp];
imageViewDown = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"1"]];
imageViewDown.layer.anchorPoint = CGPointMake(
imageViewDown.frame = CGRectMake(10, 250, 300, 150);
imageViewDown.layer.contentsRect = CGRectMake(0, 0.5, 1, 0.5);
[self.viewaddSubview:imageViewDown];
//新增一個透明浮層,用來捕捉手指滑動。
UIView *clearView = [[UIViewalloc] initWithFrame:CGRectMake(10, 100, 300, 300)];
clearView.backgroundColor = [UIColorclearColor];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizeralloc] initWithTarget:selfaction:@selector(pan:)];
[clearView addGestureRecognizer:pan];
clearView.userInteractionEnabled = YES;
clearView.tag = 100;
[self.view addSubview:clearView];
}
- (void)pan:(UIPanGestureRecognizer *)ges
{
if (ges.state == UIGestureRecognizerStateChanged) {
UIView *clearView = (UIView *)[imageViewUp viewWithTag:100];
CGPoint point = [ges translationInView:clearView];
//計算旋轉角度,拉動距離568時旋轉90度。
float R = -point.y*M_PI_2/568.0f;
CATransform3D tran = CATransform3DIdentity;
//設定摺疊視角,使之更有立體感
tran.m34 = -1.0/500.0;
imageViewUp.layer.transform = CATransform3DRotate(tran, R, 1, 0, 0);
}
elseif(ges.state == UIGestureRecognizerStateEnded)
{
//當鬆開手指時,圖片狀態恢復。
[UIView animateWithDuration:0.5fdelay:0.0foptions:UIViewAnimationOptionCurveLinearanimations:^{
imageViewUp.layer.transform = CATransform3DIdentity;
} completion:^(BOOL finished) {
nil;
}];
}
}