小工具      在线工具  汉语词典  css  js  c++  java

swift3.0图像放大缩小动画效果

Swift学习 额外说明

收录于:129天前

一、内容说明

      跟我之前这篇类似,只不过那篇是OC版本,这篇是Swift版本 OC版本链接地址

目的:通过kingfisher请求5张图片并显示。然后使用图片缩放来显示和管理图片,并且可以滑动浏览多张图片。

效果图如下。如果想看动态渲染,请看上面链接中的OC版本渲染,与本文相同。

本demo,只加载本地图片的demo该演示的下载链接,需要加载网络图片的,需要下载翠鸟



2. 源码展示

0. 图片测试demo源码

import Foundation
import UIKit

class LJPhotoGroupViewController : TFBaseViewController{

    lazy var ljArray : [LJPhotoInfo] = [LJPhotoInfo]()
    let ljUrlArray = ["http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg",
                      "http://d.lanrentuku.com/down/png/1706/10avatars-material-pngs/avatars-material-man-4.png",
                      "http://image.nationalgeographic.com.cn/2017/0703/20170703042329843.jpg",
                      "http://image.nationalgeographic.com.cn/2015/0121/20150121033625957.jpg",
                      "http://image.nationalgeographic.com.cn/2017/0702/20170702124619643.jpg"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setTopNavBarTitle("图片浏览测试Demo")
        self.setTopNavBackButton()
        self.setUI()
    }
}

extension LJPhotoGroupViewController{
    func setUI(){
       
        for index in 0...4{
            
            //1.加载本地图片
            //let image = UIImage.init(named: "\(index + 1).jpg")
            let showImageView = UIImageView.init()
            //showImageView.image = image
            showImageView.tag = index
            showImageView.frame = CGRect(x: Int((AppWidth - 200)/2.0), y: 80 + Int(90 * index), width: 200, height: 80)
            showImageView.isUserInteractionEnabled = true
            view.addSubview(showImageView)
            
            //2.加载本地图片
            let url = URL(string:ljUrlArray[index])
            showImageView.kf.setImage(with: url)
            
            let gestrue = UITapGestureRecognizer.init(target: self, action: #selector(LJPhotoGroupViewController.showClicked(_:)))
            showImageView.addGestureRecognizer(gestrue)
            
            //需要浏览的图片添加到数组
            let info = LJPhotoInfo.init()
            info.largeImageURLStr = ljUrlArray[index]
            info.thumbImageview = showImageView
            info.currentSelectIndex = index
            self.ljArray.append(info)
        }
    }
}

extension LJPhotoGroupViewController{
    
    func showClicked(_ sender : UITapGestureRecognizer){
        if self.ljArray.count > 0 {
            let index = sender.view?.tag
            let photoGroupView = LJPhotoGroupView.init(frame: CGRect(x: 0, y: 0, width: AppWidth, height: AppHeight))
            photoGroupView.setData(self.ljArray, selectedIndex: index!)
            photoGroupView.showPhotoView()
            
            CHDebugLog("-------\(String(describing: index))")
        }
    }
}


1.LJPhotoGroupView:图片浏览管理类,用于显示图片

import Foundation
import UIKit

class LJPhotoGroupView: UIView {
    
    let baseIndex = 1000
    
    var originFrame : CGRect? // 图片的源尺寸
    var currentIndex : NSInteger = 0 //当前选中的图片index
    var ljPhotoArray : [Any] = [Any]()//存储多组需要加载的图片原始信息
    
    lazy var ljScrollView : UIScrollView = {
        let view  = UIScrollView.init(frame: CGRect(x: 0, y: 0, width: AppWidth, height: AppHeight))
        view.delegate = self
        view.isPagingEnabled = true
        view.backgroundColor = UIColor.yellow
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.ljScrollView)
    }

    func setData(_ photoArray : Array<Any>, selectedIndex : NSInteger) {
        self.ljScrollView.contentSize = CGSize(width: floor(AppWidth) * CGFloat(photoArray.count), height: AppHeight)
        self.currentIndex = selectedIndex
        self.ljPhotoArray = photoArray
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LJPhotoGroupView {

// MARK: -- 图片cell复用
    func dequeueReusableCell() -> LJPhotoView {
        
        var cell = self.viewWithTag(baseIndex + self.currentIndex) as? LJPhotoView
        
        if ljPhotoArray.count > currentIndex {
            let info = ljPhotoArray[currentIndex] as? LJPhotoInfo
            let tempImageView = info?.thumbImageview

            if cell != nil{
                self.originFrame = tempImageView?.convert((tempImageView?.bounds)!, to: self)
                return cell!
            }
            
            cell = LJPhotoView.init(frame: CGRect(x: floor(AppWidth)*CGFloat(currentIndex), y: 0, width: AppWidth, height: AppHeight))
            self.originFrame = tempImageView?.convert((tempImageView?.bounds)!, to: self)
        }
        return cell!
    }
  
// MARK: -- 展示图片
    func showPhotoView(){
        
        UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(self)
        self.backgroundColor = UIColor.black
    
        let cell1 = self.dequeueReusableCell()
        cell1.tag = self.baseIndex + self.currentIndex
        
        var ljTempImage : UIImage?
        if ljPhotoArray.count > currentIndex {
            let info = ljPhotoArray[currentIndex] as? LJPhotoInfo
            ljTempImage = info?.thumbImageview?.image
        }
        
        ljTempImage = (ljTempImage != nil) ? ljTempImage : UIImage.init(named: "pic_broadcast_gray_square")
        
        let tfImageView  = UIImageView.init(image: ljTempImage)
        tfImageView.frame = self.originFrame ?? CGRect.zero
        tfImageView.clipsToBounds = true
        tfImageView.backgroundColor = UIColor.red
        tfImageView.contentMode = .scaleAspectFit
        self.addSubview(tfImageView)
        
        //添加页面消失的手势
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(hideImageView))
        self.addGestureRecognizer(tap)
        
        UIView.animate(withDuration: 0.25, animations: {
            let y : CGFloat? = (AppHeight - (ljTempImage?.size.height)! * AppWidth / (ljTempImage?.size.width)!)/2.0
            let height : CGFloat? = (ljTempImage?.size.height)! * AppWidth / (ljTempImage?.size.width)!
            tfImageView.frame = CGRect(x: 0, y: y!, width: AppWidth, height: height!)
        }) { (finish) in
            //根据选中第几张图片直接展示出来
            let cell = self.dequeueReusableCell()
            cell.tag = self.baseIndex + self.currentIndex
            cell.backgroundColor = UIColor.gray
            
            if self.ljPhotoArray.count > self.currentIndex{
                cell.setCurrentImageview(self.ljPhotoArray[self.currentIndex] as! LJPhotoInfo)
            }
            let x : CGFloat = CGFloat(self.currentIndex) * floor(AppWidth);
            self.ljScrollView.setContentOffset(CGPoint.init(x: x, y: 0), animated: false)
            self.ljScrollView.addSubview(cell)
            
            
            tfImageView.removeFromSuperview()
        }
    }
    
// MARK: -- 移除图片
    func hideImageView(){
        let cell = self.viewWithTag(baseIndex + currentIndex) as? LJPhotoView
        UIView.animate(withDuration: 0.25, animations: {
            cell?.ljImageView.frame = self.originFrame!
        }) { (finish) in
            self.backgroundColor = UIColor.white
            self.removeFromSuperview()
        }
    }
}

extension LJPhotoGroupView : UIScrollViewDelegate{
   
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //滑动时,会调用多次
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
     //滑动完毕时,只会调用一次
        let page = self.ljScrollView.contentOffset.x / self.frame.size.width;
        self.currentIndex = NSInteger(page);
        print("scrollViewDidEndDecelerating当前页数----\(page)")
        
        let cell = self.dequeueReusableCell()
        cell.tag = self.baseIndex + Int(page)
        if self.ljPhotoArray.count > self.currentIndex{
            cell.setCurrentImageview(self.ljPhotoArray[self.currentIndex] as! LJPhotoInfo)
        }
        self.ljScrollView.addSubview(cell)
    }
}


2. 丽津图片资料:图片信息的model

import Foundation
import UIKit

class LJPhotoInfo: NSObject {
    
    var currentSelectIndex : Int?
    var largeImageURLStr : String?
    var thumbImageview : UIImageView?
    
    override init() {
        super.init()
    }
}


3.LJPhotoView:图片浏览管理类使用的cell(图片展示)

import Foundation
import UIKit

class LJPhotoView: UIScrollView {
    
    var ljInfo : LJPhotoInfo?
    
    lazy var ljImageView : UIImageView = {
            let view = UIImageView()
            view.clipsToBounds = true
            view.contentMode = .scaleAspectFit
            return view
        }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.zoomScale = 1.0
        self.addSubview(self.ljImageView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LJPhotoView{
    func setCurrentImageview(_ info : LJPhotoInfo){
        self.ljInfo = info
        if self.ljInfo?.thumbImageview?.image == nil{
           self.ljInfo?.thumbImageview?.image = UIImage.init(named: "pic_broadcast_gray_square")
        }
        
        //无url,则通过thumbImageview获取Image展示
        //self.ljImageview.image = info.thumbImageview.image;
        let y : CGFloat? = (AppHeight - (info.thumbImageview?.image?.size.height)! * AppWidth / (info.thumbImageview?.image?.size.width)!) * 0.5;
        self.ljImageView.frame = CGRect(x: 0, y: y!, width: AppWidth, height: AppWidth*(info.thumbImageview?.image?.size.height)!/(info.thumbImageview?.image?.size.width)!)
        self.ljImageView.image = self.ljInfo?.thumbImageview?.image
        
        if info.largeImageURLStr != "" {
            let url = URL(string:info.largeImageURLStr!)
            self.ljImageView.kf.setImage(with: url)
        }
    }
}


. . .

相关推荐

额外说明

REDIS13_缓存雪崩、缓存穿透、基于布隆过滤器解决缓存穿透问题、缓存击穿、基于缓存击穿的实战案例

文章目录 ①. 缓存雪崩 ②. 缓存穿透 ③. 在centos7下布隆过滤器2种安装方式 ④. 缓存击穿 ⑤. 高并发的淘宝聚划算案例落地 ①. 缓存雪崩 ①. 问题的产生:缓存雪崩是指缓存数据大批量到过期时间,而查询数据量巨大,引起数据库压力过大甚至d

额外说明

python 面向对象编程

文章目录 前言 如何理解面向对象编程 在 python 中如何使用面向对象编程 定义类 创建对象 self 添加和获取对象属性 添加属性 类外添加属性 类中添加属性 访问属性 类外访问属性 类中访问属性 魔法方法 __ init __() 方法 __ s

额外说明

程序员面试 10 大潜规则,千万不要踩坑!

1.大纲 潜规则1:面试的本质不是考试,而是告诉面试官你会做什么 很多刚入行的小伙伴特别容易犯的一个错误,不清楚面试官到底想问什么,其实整个面试中面试官并没有想难道你的意思,只是想通过提问的方式来知道你会什么 比如: 面试官提问在实际项目中你们是怎么样使

额外说明

java多线程设计模式之GuardSuspension模式

     Guard是被守护被保卫的意思,我们可以将GuardSuspension模式看作是singgleThreadExcution模式和一个判断条件所组成的,这么叙述太笼统,可以结合下面的案例来体会一下这个过程:    我们模拟的是客户端向服务器端发

额外说明

【PHP面试题31】PHP写出3中以上获取文件名后缀的方法

文章目录 一、前言 二、具体实现 方法1:使用substr函数截取字符串 方法2:使用pathinfo函数获取文件扩展名 方法3:使用explode函数分割字符串 方法4:使用正则表达式获取后缀 方法5:使用strrev函数和strpos函数获取后缀 三

额外说明

Java字符串替换 replaceAll 使用解析

从 Dangling meta character 的错误开始 有一个字符串。 里面包含符号加号(+), 现在使用replaceAll() 方法将所有的加号替换为下划线 (_), 示例代码如下: String str = "+";

额外说明

torch.stack() & torch.repeat() & torch.repeat_interleave() & torch转置 详解

torch.stack((a,b),dim=n) 把tensor按垂直方向堆起来 h1=torch.tensor([1, 1, 1, 1]) h2=torch.tensor([2, 2, 2, 2]) result = torch.stack((h1,h

额外说明

【软考 系统架构设计师】嵌入式系统② 总线

>>回到总目录<< 为了不辜负已经订阅了专栏的同学们的信任,所以本专栏不会有任何的优惠活动。 另外,当订阅人数每次达到 2 n ( n > 2 ) 2^n(n>2) 2

额外说明

如何自动将精选图片链接到WordPress中的帖子

最近,我们的一位读者询问是否可以将特色图像自动链接到 WordPress 中的博客文章。大多数 WordPress 主题默认将精选图像链接到帖子,但某些主题可能不会这样做。在本文中,我们将向您展示如何自动将图片链接到 WordPress 中的帖子。 最近

额外说明

如何在WordPress中显示最受欢迎的标签

您想显示 WordPress 网站上最常用的标签吗?标签和类别是 WordPress 中对内容进行排序的两种默认方式。由于类别范围更广,类别通常会获得更多曝光,这使得标签受到的关注较少。在本文中,我们将向您展示如何轻松地在 WordPress 中显示最流

ads via 小工具