IOS:在scrollview中添加imageview以进行缩放

我想用UIImage设置一个UIImageView,并把这个ImageView放在一个UIScrollView来获得这个图像的缩放; 我想这个UIImageViewUIScrollView适合在视图的中心rect …是否有可能?

  1. 将视图控制器设置为<UIScrollViewDelegate>
  2. 在视图的中心绘制您想要的矩形大小的UIScrollView 。 将检查器中的最大放大倍数设置为大于1的值。例如4或10。
  3. 右键单击滚动视图并将代理连接到您的视图控制器。
  4. UIScrollView绘制你的UIImageView ,并设置你想要的任何图像。 使其尺寸与UIScrollView相同。
  5. 按住Ctrl键,将UIImageView拖动到View控制器的.h ,为UIImageView创build一个IBOutlet ,称之为像imageView这样的巧妙操作。
  6. 添加以下代码:

     -(UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView { return self.imageView; } 
  7. 运行应用程序,捏,直到你的心的内容。

下载这个和这个文件。 你需要他们来处理触摸。

添加到您的视图scrollView委托<UIScrollViewDelegate>并声明网点:

  @property (nonatomic, retain) IBOutlet UIScrollView *imageScrollView; @property (nonatomic, retain) UIImageView *imageView; 

在屏幕中导入下载的文件,然后执行:

 #import "TapDetectingImageView.h" #define ZOOM_STEP 2.0 @interface myView (UtilityMethods) - (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center; @end @implementation myView @synthesize imageScrollView, imageView; - (void)viewDidLoad { [super viewDidLoad]; //Setting up the scrollView imageScrollView.bouncesZoom = YES; imageScrollView.delegate = self; imageScrollView.clipsToBounds = YES; //Setting up the imageView imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage.png"]]; imageView.userInteractionEnabled = YES; imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin); //Adding the imageView to the scrollView as subView [imageScrollView addSubview:imageView]; imageScrollView.contentSize = CGSizeMake(imageView.bounds.size.width, imageView.bounds.size.height); imageScrollView.decelerationRate = UIScrollViewDecelerationRateFast; //UITapGestureRecognizer set up UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)]; UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)]; UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTap:)]; [doubleTap setNumberOfTapsRequired:2]; [twoFingerTap setNumberOfTouchesRequired:2]; //Adding gesture recognizer [imageView addGestureRecognizer:doubleTap]; [imageView addGestureRecognizer:twoFingerTap]; [singleTap release]; [doubleTap release]; [twoFingerTap release]; // calculate minimum scale to perfectly fit image width, and begin at that scale float minimumScale = 1.0;//This is the minimum scale, set it to whatever you want. 1.0 = default imageScrollView.maximumZoomScale = 4.0; imageScrollView.minimumZoomScale = minimumScale; imageScrollView.zoomScale = minimumScale; [imageScrollView setContentMode:UIViewContentModeScaleAspectFit]; [imageView sizeToFit]; [imageScrollView setContentSize:CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)]; } - (void)scrollViewDidZoom:(UIScrollView *)aScrollView { CGFloat offsetX = (imageScrollView.bounds.size.width > imageScrollView.contentSize.width)? (imageScrollView.bounds.size.width - imageScrollView.contentSize.width) * 0.5 : 0.0; CGFloat offsetY = (imageScrollView.bounds.size.height > imageScrollView.contentSize.height)? (imageScrollView.bounds.size.height - imageScrollView.contentSize.height) * 0.5 : 0.0; imageView.center = CGPointMake(imageScrollView.contentSize.width * 0.5 + offsetX, imageScrollView.contentSize.height * 0.5 + offsetY); } - (void)viewDidUnload { self.imageScrollView = nil; self.imageView = nil; } #pragma mark UIScrollViewDelegate methods - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return imageView; } #pragma mark TapDetectingImageViewDelegate methods - (void)handleDoubleTap:(UIGestureRecognizer *)gestureRecognizer { // zoom in float newScale = [imageScrollView zoomScale] * ZOOM_STEP; if (newScale > self.imageScrollView.maximumZoomScale){ newScale = self.imageScrollView.minimumZoomScale; CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]]; [imageScrollView zoomToRect:zoomRect animated:YES]; } else{ newScale = self.imageScrollView.maximumZoomScale; CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]]; [imageScrollView zoomToRect:zoomRect animated:YES]; } } - (void)handleTwoFingerTap:(UIGestureRecognizer *)gestureRecognizer { // two-finger tap zooms out float newScale = [imageScrollView zoomScale] / ZOOM_STEP; CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]]; [imageScrollView zoomToRect:zoomRect animated:YES]; } #pragma mark Utility methods - (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center { CGRect zoomRect; // the zoom rect is in the content view's coordinates. // At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds. // As the zoom scale decreases, so more content is visible, the size of the rect grows. zoomRect.size.height = [imageScrollView frame].size.height / scale; zoomRect.size.width = [imageScrollView frame].size.width / scale; // choose an origin so as to get the right center. zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0); zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0); return zoomRect; } 

完成!

基本上这个代码做的是添加imageScrollView作为imageScrollView子视图。

然后,它将TapDetecting类的方法添加到scrollView中,以便识别水龙头的数量 – 用户捏合并添加缩放function。

你可以设置图像的minimumScale ,如果你离开1.0 ,图像应该是原样显示的(如果你把它设置得小一点,那么缩放),最大缩放比例,我build议你把它保留为4,没关系!

现在,您可以从这里以编程方式加载图像。

你必须做的最后一件事就是在你的xib文件中插入一个UIScrollView并将其链接到imageScrollView 。 你将在完美的中心有图像,你可以双击它来缩放,捏放大,你设置在代码。

我已经写了一个示例应用程序,它也支持AutoLayout和Storyboards来演示这种行为。 我希望能够节省每个人的时间,试图弄清楚这一点: http : //rexstjohn.com/facebook-like-ios-photo-modal-gallery-swipe-gestures/ 。

使用Swift 4和iOS 11,您可以使用以下代码来依靠自动布局来解决您的问题:

ViewController.swift

 import UIKit class ViewController: UIViewController { private let scrollView = ImageScrollView(image: UIImage(named: "image")!) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.updateMinZoomScaleForSize(view.bounds.size) } } 

ImageScrollView.swift

 import UIKit class ImageScrollView: UIScrollView { private let imageView = UIImageView() private var imageViewBottomConstraint = NSLayoutConstraint() private var imageViewLeadingConstraint = NSLayoutConstraint() private var imageViewTopConstraint = NSLayoutConstraint() private var imageViewTrailingConstraint = NSLayoutConstraint() required init(image: UIImage) { super.init(frame: .zero) imageView.image = image imageView.sizeToFit() addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor) imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor) imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor) imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor) NSLayoutConstraint.activate([imageViewLeadingConstraint, imageViewTrailingConstraint, imageViewTopConstraint, imageViewBottomConstraint]) contentInsetAdjustmentBehavior = .never // Adjust content according to safe area if necessary showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false alwaysBounceHorizontal = true alwaysBounceVertical = true delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } 
 extension ImageScrollView: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { updateConstraintsForSize(bounds.size) } // MARK: - Helper methods func updateMinZoomScaleForSize(_ size: CGSize) { let widthScale = size.width / imageView.bounds.width let heightScale = size.height / imageView.bounds.height let minScale = min(widthScale, heightScale) minimumZoomScale = minScale zoomScale = minScale } private func updateConstraintsForSize(_ size: CGSize) { let yOffset = max(0, (size.height - imageView.frame.height) / 2) imageViewTopConstraint.constant = yOffset imageViewBottomConstraint.constant = yOffset let xOffset = max(0, (size.width - imageView.frame.width) / 2) imageViewLeadingConstraint.constant = xOffset imageViewTrailingConstraint.constant = xOffset layoutIfNeeded() } } 

资料来源:

  • Github / ImageScrollView
  • raywenderlich.com / UIScrollView教程:入门