swift 放大缩小自定义 Scrollview

//

//  ZoomScaleWithGestureScrollView.swift

//  UIControlDemo

//

//  Created by   on 14/12/3.

//  Copyright (c) 2014 马大哈. All rights reserved.

//  协议  

 

// 枚举类型

enum ImageLoadType {

    case ImageNamed ,ImageBundle ,ImageDocument ,ImageUrl

   

}

 

protocol ZoomScaleDelegate{

    func tapMethod()

}

 

import UIKit

 

class ZoomScaleWithGestureScrollView: UIScrollView ,UIScrollViewDelegate{

   

    var imageView:UIImageView?

    var deleZoom:ZoomScaleDelegate?

    

    init(frame: CGRect ,loadType:ImageLoadType ,loadUrl:String) {

        super.init(frame: frame)

       

        delegate = self

        minimumZoomScale = 0.5

        maximumZoomScale = 2.0

        showsHorizontalScrollIndicator = false

        showsVerticalScrollIndicator   = false

        backgroundColor = .redColor()

    

        imageView = UIImageView(frame: CGRectMake(0, 50, frame.size.width, frame.size.height))

        imageView?.contentMode = UIViewContentMode.ScaleAspectFit

        self.addSubview(imageView!)

        imageView?.userInteractionEnabled = true

        

        switch loadType {

        case .ImageNamed:

            imageView?.image = UIImage(named: loadUrl)

        case .ImageBundle:

            // "imageName.png" ----> imageName   png

            let imageName = loadUrl.componentsSeparatedByString(".")

            let imageBundle = NSBundle.mainBundle().pathForResource(imageName[0], ofType: imageName[1])

            imageView?.image = UIImage(contentsOfFile: imageBundle!)

        case .ImageDocument:

            //传过来参数 文件夹 # 图片名字

            let imageDocument = loadUrl.componentsSeparatedByString("#")

            imageView?.image = UIImage(contentsOfFile: parseImageAddress(imageDocument[1], directory: imageDocument[0]))

        case .ImageUrl:

            // utf8 转义,防止中文路径无法读取   !表示一定存在

            let loadString = loadUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

            let urlString = NSURL(string: loadString!)

            let imageData = NSData(contentsOfURL: urlString!)

            imageView?.image = UIImage(data: imageData!)

        default :

            println()

        }

 

        var gestureOne = UITapGestureRecognizer(target: self, action: "tapOne")

        var gestureTwo = UITapGestureRecognizer(target: self, action: "tapTwo")

        gestureTwo.numberOfTapsRequired = 2

        gestureOne.requireGestureRecognizerToFail(gestureTwo)//加此代码防止双击动作调用单击方法(反之,两个方法都会调用)

        imageView?.addGestureRecognizer(gestureOne)

        imageView?.addGestureRecognizer(gestureTwo)

 

    }

  

    //”需要初始化”init(编码器:)”的子类必须提供“UIScrollView”

    //UIView采用NSCoding协议,需要一个init初始化器(编码器:)。所以你必须实现

    required init(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    

    func tapTwo(){

        var zoomF:CGFloat = self.zoomScale

        if zoomF==1.0{

            zoomF = 2.0

        }else{

            zoomF = 1.0

        }

        UIView.animateWithDuration(0.3, animations:{

            self.zoomScale = zoomF

        }) 

    }

    

    // 单击调用协议方法

    func tapOne(){

        deleZoom?.tapMethod()

        

    }

     

    func parseImageAddress(imageUrl: String ,directory:String) -> String{

        var parserColon = imageUrl.stringByReplacingOccurrencesOfString(":", withString: "", options: .CaseInsensitiveSearch, range: nil)//替换 ---冒号

        var parserHttp  = parserColon.stringByReplacingOccurrencesOfString("http://", withString: "", options: .CaseInsensitiveSearch, range: nil)//替换 ---http://

        var parserBias  = parserHttp.stringByReplacingOccurrencesOfString("/", withString: "", options: .CaseInsensitiveSearch, range: nil)//替换 ---/

 

        let application = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)

        let documentString = application[0] as String     

        var imageAddress = documentString.stringByAppendingPathComponent(parserBias)

        if directory.isEmpty {

        }else{

            imageAddress = documentString.stringByAppendingPathComponent("\(directory)/\(parserBias)")

        }

        return imageAddress

    }

            

    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {

        return imageView

    }

 

    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) {

        var zoomF = scrollView.zoomScale

        zoomF = max(zoomF, 1.0);

        zoomF = min(zoomF, 2.0)

        UIView.animateWithDuration(0.3, animations:{

            scrollView.zoomScale = zoomF

        })

    }

 

}

 

************************************************************************************************

调用方法 执行  ZoomScaleDelegate  协议  ,实现 tapMethod 协议方法 

        zoomScroll = ZoomScaleWithGestureScrollView(frame: CGRectMake(0, 0, self.view.frame.size.width, 300), loadType: ImageLoadType.ImageNamed, loadUrl: "test_DiamondInlay_goods_0.jpg")

//        zoomScroll = ZoomScaleWithGestureScrollView(frame: CGRectMake(0, 0, self.view.frame.size.width, 300), loadType: ImageLoadType.ImageBundle, loadUrl: "test_DiamondInlay_goods_7.jpg")

//        zoomScroll = ZoomScaleWithGestureScrollView(frame: CGRectMake(0, 0, self.view.frame.size.width, 300), loadType: ImageLoadType.ImageDocument, loadUrl: "imageFile#test_DiamondInlay_goods_1.jpg")//前面是文件夹,可为空

//        zoomScroll = ZoomScaleWithGestureScrollView(frame: CGRectMake(0, 0, self.view.frame.size.width, 300), loadType: ImageLoadType.ImageUrl, loadUrl: "http://ww2.sinaimg.cn/bmiddle/632dab64jw1ehgcjf2rd5j20ak07w767.jpg")

        zoomScroll?.deleZoom = self

        self.view.addSubview(zoomScroll!)

 

 

 

posted on 2014-12-09 20:46  马大哈哈  阅读(421)  评论(0编辑  收藏  举报

导航