智能手机一般常用常用的操作触摸,滑动,缩放,感觉对于生活而言就是手机在手,天下我有,看网页的时候字体太小,缩放一下,看美女的看的不爽,缩放一下,地图看的不清,缩放一下。缩放是一个很常见的操作,不论是从生活还是写程序而言,都是一个绕不开的东西,做了一个Demo,缩放一下美女,熟悉ScrollView中的常见属性的设置,开始正题吧。
常见属性
先看图,要实现的效果:
UIImage *image=[UIImage imageNamed:@"girl0.jpg"];
_imageView=[[UIImageView alloc] initWithImage:image];
[_scrollView addSubview:_imageView];
//设置ScrollView和image是一样的大小
[_scrollView setContentSize:image.size];
可以设置ScrollView的初始位置和大小:
//CGRect枚举一个矩形,然后设置imageView的位置
[_imageView setFrame:CGRectMake(0, 0, 100, 100)];
设置边界区域:
//设置边界区域
[_scrollView setContentInset:UIEdgeInsetsMake(20, 20.0, 20.0, 20.0)];
上下左右移动调用哪个同意IBAction,通过Tag区分(之前文章有介绍),移动就是控制坐标,IOS中左上角是0,X轴向右自增,Y轴向下自增:
UIButton *button=(UIButton *)sender;
CGPoint currentPoint=self.scrollView.contentOffset;
switch (button.tag) {
case 0:
currentPoint.y-=50;
break;
case 1:
currentPoint.y+=50;
break;
case 2:
currentPoint.x-=50;
break;
case 3:
currentPoint.x+=50;
break;
default:
break;
}
//横轴的边界值
if (currentPoint.x<0) {
currentPoint.x=0;
}else if (currentPoint.x>_scrollView.contentSize.width-_scrollView.bounds.size.width){
currentPoint.x=_scrollView.contentSize.width-_scrollView.bounds.size.width;
}
//纵轴的边界值
if (currentPoint.y<0) {
currentPoint.y=0;
}else if (currentPoint.y>_scrollView.contentSize.height-_scrollView.bounds.size.height){
currentPoint.y=_scrollView.contentSize.height-_scrollView.bounds.size.height;
}
//动画效果
[self.scrollView setContentOffset:currentPoint animated:YES];
动画效果可以通过block设置:
[UIView animateWithDuration:0.3f animations:
^{
[self.scrollView setContentOffset:currentPoint];
}];
缩放
缩放之前需要涉及到一个东西就是控制器需要遵守UIScrollViewDelegate协议,然后实现协议中方法,应用场景中如果我们在对ScrollView中图片进行缩放,将消息通知给UIScrollViewDelegate,最终将事件实现委托给是实现方法:
//
// ViewController.h
// ScrollView
// http://www.cnblogs.com/xiaofeixiang
// Created by keso on 15/1/20.
// Copyright (c) 2015年 keso. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end
设置一下最大和最小缩放比例,设置委托:
[_scrollView setMinimumZoomScale:0.3];
[_scrollView setMaximumZoomScale:1.8];
[_scrollView setDelegate:self];
实现一个返回的图像,如果不是实现,没有效果:
//缩放过程中的图像
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return _imageView;
}
有的时候如果可能有业务需要会需要一个缩放结束的方法:
缩放结束
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
NSLog(@"缩放比例:%f",scale);
}
还有一个不常用的,缩放中的方法:
//缩放中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
NSLog(@"缩放中的调用~");
}
最终效果: