2019-08-19 16:08:44 dongdong_yan 阅读数 196

     当我们项目中有关于图片的功能时,就免不了需要用到图片上传。

     但是,我们要认识到,你要上传的图片大小,是否是必须的。当我们确定要上传的图片,只是用在手机端显示,并不是必须使用原图,这时,我们要在上传前,进行图片的压缩。

     swift提供了较简单的压缩方法:

     

var imageData: Data = image.jpegData(compressionQuality: 0.3) ?? Data()

      但是,这个方法有个问题,当压缩比例太小时,就会固定在某个极限值,我个人粗略估算,大约是0.02

       因此,当图片足够大,而我们只是用来当类似头像来使用时,上述方法就那以满足了。在此,我提供一个另外的方法:将图片重新绘制,以大量减小图片大小   

    /**
     *  等比率缩放
     */
    func scaleImage(scaleSize:CGFloat)->UIImage {
        let reSize = CGSize(width:self.size.width * scaleSize, height:self.size.height * scaleSize)
        return reSizeImage(reSize: reSize)
    }
    /**
     *  重设图片大小
     */
    func reSizeImage(reSize:CGSize)->UIImage {
        UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.main.scale);
        self.draw(in: CGRect(x:0, y:0, width:reSize.width, height:reSize.height));
        let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage();
        UIGraphicsEndImageContext();
        return reSizeImage;
    }

 

2017-07-13 20:58:58 moqj_123 阅读数 2220

场景:我们在使用app的时候,特别是显示多张图片的时候,都会点击图片并进行浏览,比如QQ、微信,好友发表的动态,我们都会点击进去查看原图。现在很多app都支持图片浏览功能,这样更加方便用户体验,那么我们在项目开发过程中,怎么对图片点击进行预览,下面介绍一下在swift项目开发中使用SDPhotoBrowser进行图片浏览。

SDPhotoBrowser地址:https://github.com/gsdios/SDPhotoBrowser

下面直接代码进行说明

//
//  ShopStoreTableHeaderView.swift
//  SmartMilk
//
//  Created by lin jiang on 2017/7/11.
//  Copyright © 2017年 greengao. All rights reserved.
//

import UIKit

//添加SDPhotoBrowserDelegate代理
class ShopStoreTableHeaderView: UIView,UIScrollViewDelegate,SDPhotoBrowserDelegate {

    var storeImages:NSMutableArray = NSMutableArray()
    var mainScrollView:UIScrollView?
    var mainPageControl:UIPageControl?
    var mainTimer:Timer?
    
    var isMiddleShow:Bool = false
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setScrollViewUI()
        setPageControlUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setScrollViewUI(){
        self.mainScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.width, height: self.height))
        
        // 添加到父视图
        self.addSubview(self.mainScrollView!)
        
        // 背景颜色
        //        arc4random()
        self.mainScrollView?.backgroundColor = UIColor.white
        
        
        // 自适应父视图
        // self.mainScrollView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
        // 其他属性
        self.mainScrollView?.isScrollEnabled = true // 上下滚动
        self.mainScrollView?.scrollsToTop = true // 点击状态栏时,可以滚动回顶端
        self.mainScrollView?.bounces = true // 在最顶端或最底端时,仍然可以滚动,且释放后有动画返回效果
        mainScrollView?.isPagingEnabled = true // 分页显示效果
        mainScrollView?.showsHorizontalScrollIndicator = false // 显示水平滚动条
        mainScrollView?.showsVerticalScrollIndicator = true // 显示垂直滚动条
        mainScrollView?.indicatorStyle = UIScrollViewIndicatorStyle.white // 滑动条的样式
        // 设置内容大小
        // self.mainScrollView?.contentSize = CGSize(width: originX, height: scrollViewHeight)
        
        
        // 代理
        self.mainScrollView?.delegate = self
    }
    
    func setPageControlUI(){
        self.mainPageControl = UIPageControl(frame: CGRect(x: (self.width - 150.0) / 2, y: ((self.mainScrollView?.bounds)!.height - 20.0 - 10.0), width: 150.0, height: 20.0))
        
        // 添加到父视图
        self.addSubview(self.mainPageControl!)
        // 背景颜色
        self.mainPageControl?.backgroundColor = UIColor.clear
        
        // 其他属性设置
        self.mainPageControl?.numberOfPages = 0 // 总页数
        self.mainPageControl?.currentPage = 0 // 当前页数,默认为0,即第一个,实际数量是0~n-1
        self.mainPageControl?.pageIndicatorTintColor = UIColor.lightGray // 非当前页颜色
        self.mainPageControl?.currentPageIndicatorTintColor = UIColor.red // 当前页颜色

    }
    
    func setMainScrollViewPageControl(images:[StoreImageModel]) {
        self.storeImages.removeAllObjects()
        self.storeImages.addObjects(from: images)
        
        for view  in (self.mainScrollView?.subviews)! {
            view.removeFromSuperview()
        }
        var originX:CGFloat = 0.0
        for model in images
        {
            let imageView = UIImageView(frame: CGRect(x:originX, y:0.0, width:SCREEN_WIDTH, height:self.height))
            
            let url = URL(string: model.storeSmallImg!)
            
            let image = UIImage(named: "default_icon")
            
            // weak var weakSelf = self
            imageView.sd_setImage(with: url, placeholderImage: image, options: .retryFailed, completed: { (image, error, cacheType, URL) in
                
            })
            //添加UI Image View的点击事情
            let tap = UITapGestureRecognizer(target: self, action: #selector(onClickedImageEvent(gest:)))
            imageView.isUserInteractionEnabled = true
            
            imageView.addGestureRecognizer(tap)
            
            //主要是显示区分显示大点的图和小点的图
            if isMiddleShow == true{
                
                let contentView = UIView(frame: CGRect(x:originX, y:0.0, width:self.width, height:self.height))
                let imagexx = (SCREEN_WIDTH - self.height)/2
                
                imageView.frame = CGRect(x:imagexx, y:0.0, width:self.height, height:self.height)
                
                contentView.addSubview(imageView)
                self.mainScrollView?.addSubview(contentView)
                originX = (contentView.frame.minX + contentView.frame.width)
            }
            else
            {
                self.mainScrollView?.addSubview(imageView)
                
                originX = (imageView.frame.minX + imageView.frame.width)
            }
            
           
        }
        self.mainScrollView?.contentSize = CGSize(width: originX, height: self.height)
        
        self.mainPageControl?.numberOfPages = images.count // 总页数
        self.mainPageControl?.currentPage = 0 // 当前页数,默认为0,即第一个,实际数量是0~n-1
        
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        MQLog(message:"6 scrollViewDidEndDecelerating")
        
        let width = scrollView.frame.width
        let offsetX = scrollView.contentOffset.x
        let index = offsetX / width
        MQLog(message:"当前页是:\(index)")
        
        self.mainPageControl?.currentPage = Int(index)
    }
    
    func addTimer()
    {
        self.mainTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(autoShow), userInfo: nil, repeats: true)
    }
    
    func removerTimer()
    {
        if self.mainTimer != nil
        {
            self.mainTimer?.invalidate()
            self.mainTimer = nil
        }
    }
    
    
    func autoShow()
    {
        var page:Int = (self.mainPageControl?.currentPage)!
        let total = (self.mainPageControl?.numberOfPages)! - 1
        if total == page
        {
            page = 0
        }
        else
        {
            page += 1
        }
        
        // 设置偏移量
        let offsetX = CGFloat(page) * (self.mainScrollView?.frame)!.width
        self.mainScrollView?.setContentOffset(CGPoint(x:offsetX, y:0.0), animated: true)
        self.mainPageControl?.currentPage = page
    }
    
    
    func onClickedImageEvent(gest:UITapGestureRecognizer) {
        
        
        let browser = SDPhotoBrowser()
        
        //显示图片UIImageView的父控件
        browser.sourceImagesContainerView =  self.mainScrollView
        
        //显示图片的总数量
        browser.imageCount = self.storeImages.count
        
        //
        if self.storeImages.count > (self.mainPageControl?.currentPage)! {
            browser.currentImageIndex = (self.mainPageControl?.currentPage)!
        }
        else
        {
            //要显示的当前图片下标位置
            browser.currentImageIndex = 0
        }
        
        browser.delegate = self
        browser.show()
    }
    
    /**************************************************************/
    //返回当前UIImageView显示的图片
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        if self.isMiddleShow{
            let contentView = self.mainScrollView?.subviews[index]
            let imageView:UIImageView = contentView?.subviews[0]as! UIImageView
            
            return imageView.image
        }
        else
        {
            let imageView:UIImageView = self.mainScrollView?.subviews[index]as! UIImageView
            
            return imageView.image
        }
        
    }
    
    //设置要显示图片资源的地址
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        
        let model = self.storeImages[index] as! StoreImageModel
        
        let url = URL(string: model.storeBigImg!)
        
        return url
        
    }


}

运行结果:以上图片资源的地址就不提供了,是公司的资源,百度随便找几张图片就可以了

  



2016-03-30 15:39:28 qq_31394809 阅读数 273

图片的无限轮播难点在播放到最后一个图片时候怎么无暇接到第一张图片?

这里的解决办法就是,首先创建出三个UIImageView,分别命名为a,b,c,我们在ScrollView中看到的是b,当图片滚动到右边的c时,我们在后台悄悄的把这三个UIImageView更换掉,变为b,c,d,再将ScrollView的显示内容设置为c,酱紫我们看到的内容就不会变。这样的好处就是无论多少张图片,我们只拿三张,而且当滚动到最后一张时候,也能接上第一张。

下面我们看代码:

class ViewController: UIViewController,UIScrollViewDelegate {


    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var pageControl: UIPageControl!


    var timer :NSTimer!            //定时器

    var sumArray : [String] = []   //共多少个图片

    var showArray : [String] = []  //拿出三个图片

    let totalCount = 5             //设置滚动的图片数量

    var imageWidth = CGFloat()     //scrollView的宽度

    var imageHeight = CGFloat()    //scrollView的高度

    

    override func viewDidLoad() {

        super.viewDidLoad()

        imageWidth = scrollView.bounds.width

        imageHeight = scrollView.bounds.height

        //添加图片到数组中

        for _ in 0..<totalCount {

            sumArray.append("background")

        }

        

        loadImage()

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

    

    //加载图片

    func loadImage() {

        changeShowArray()

        //根据showArray提供的数据,创建三个UIImageView

        for index in 0..<showArray.count {

            let image = UIImageView(image: UIImage(named: showArray[index]))

            image.frame = CGRect(x: CGFloat(index)*imageWidth, y: 0, width: imageWidth, height: imageHeight)

            scrollView.addSubview(image)

        }

        scrollView.contentSize = CGSize(width: CGFloat(totalCount) * imageWidth, height: imageHeight)

        scrollView.pagingEnabled = true

        scrollView.showsHorizontalScrollIndicator = false

        scrollView.delegate = self

        //让scrollView显示在三个UIImageView的中间位置

        scrollView.setContentOffset( CGPoint(x: imageWidth,y: 0), animated: false)

        //设置定时器

        timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("nextImage"), userInfo: nil, repeats: true)

    }

    

    //下一张图片

    func nextImage() {

        self.scrollView.setContentOffset( CGPoint(x: CGFloat(2) * self.imageWidth,y: 0), animated: true)

    }

    

    //当scrollView的contentOffset发生变化时调用

    func scrollViewDidScroll(scrollView: UIScrollView) {

         //判断是不是这个scrollView,可能存在多个scrollView的contentOffset发生变化

        if scrollView != scrollView{

            return

        }

        

        let x = scrollView.contentOffset.x

        var page = pageControl.currentPage

        //根据contentOffset.x判断page,从而获得显示内容

        if x >= 2 * imageWidth {

            page = (page + 1) % 5    //0的下一页 1,2,3,4,0

            pageControl.currentPage = page

            changeShowView()

        }else if x <= 0 {

            page = (page + 4) % 5    //0的上一页 4,3,2,1,0

            pageControl.currentPage = page

            changeShowView()

        }

    }

    

    //改变showArray数组

    func changeShowView() {

        changeShowArray()

        //获取scrollView的所有子元素(UIImageView),放在一个数组里,再从showArray里拿到数据,给UIImageView赋值

        var  scrollImages = scrollView.subviews as! [UIImageView]

        for (index,imageStr) in showArray.enumerate() {

            scrollImages[index] =  UIImageView(image: UIImage(named: imageStr))

        }

        //所有UIImageView改变完之后,重新将scrollView显示在三个UIImageView的中间位置

        scrollView.setContentOffset(CGPoint(x: imageWidth, y: 0), animated: false)

    }

    

    //改变showArray的数组

    func changeShowArray() {

        let page = pageControl.currentPage

        //根据当前的page判断前后两个page

        switch page {

            case 0 :

                setShowArray(sumArray.count - 1, current: page, last: page + 1)

            case sumArray.count - 1 :

                setShowArray(page - 1, current: page, last: 0)

            default :

                setShowArray(page - 1, current: page, last: page + 1)

        }

    }

    

    //showArray的排列顺序添加规则

    func setShowArray(frist : Int,current :Int,last : Int) {

        showArray.removeAll()

        showArray.append(sumArray[frist])

        showArray.append(sumArray[current])

        showArray.append(sumArray[last])

    }

    

}


2017-09-07 14:27:54 bitcser 阅读数 1364

新建个swift类,设置为UIImage的类别,UIImage对象调用该方法就返回添加水印之后的Image对象了

import Foundation
import UIKit
extension UIImage {
    func drawTextInImage()->UIImage {
        //开启图片上下文
        UIGraphicsBeginImageContext(self.size)
        //图形重绘
        self.draw(in: CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height))
        //水印文字属性
        let att = [NSForegroundColorAttributeName:UIColor.red,NSFontAttributeName:UIFont.systemFont(ofSize: 60),NSBackgroundColorAttributeName:UIColor.green]
        //水印文字大小
        let text = NSString(string: "**集团")
        let size =  text.size(attributes: att)
        //绘制文字
        text.draw(in: CGRect.init(x: self.size.width-450, y: self.size.height-80, width: size.width, height: size.height), withAttributes: att)
        //从当前上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image!
        
    }
}


2016-09-06 16:29:17 qq_27881217 阅读数 244

每天在公司实习学习,公司需要用Swift,所以开始接触Swift,决定把自己每天学到的知识记录下来,新手初探,欢迎指正和交流

import UIKit

class HomeViewController: UIViewController,UIScrollViewDelegate {

//定义需要的控件
1.UIPageControl
2.UIScrollView

var pageControl = UIPageControl()

var scrollView=UIScrollView()
override func viewDidLoad() {
    super.viewDidLoad()
   self.view.backgroundColor=UIColor.orangeColor()
    self.title="首页"
    //定时器:用于自动切换图片(每隔三秒)
     NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: #selector(HomeViewController.pageNumberChanged(_:)), userInfo: nil, repeats: true)

//ScrollView的初始化
scrollView=UIScrollView(frame:CGRectMake(0, 0, view.bounds.size.width, 200))

    scrollView.backgroundColor=UIColor.blackColor()
    scrollView.showsHorizontalScrollIndicator=false
    scrollView.showsVerticalScrollIndicator=false

    //代理
    scrollView.delegate=self

    creatPageControl()

//在ScrollView上添加三张图片    
    //let imageV=UIImageView(image: UIImage(named: "scroll.jpg"))

    let image1=UIImageView(image: UIImage(named: "scroll.jpg"))
    let image2=UIImageView(image: UIImage(named: "2222.jpg"))

    let image3=UIImageView(image: UIImage(named: "333.jpg"))

//三张图片一次排列到ScrollView上    
    image1.frame=CGRectMake(0, 0, SCREEN_WIDTH, scrollView.frame.size.height)
    image2.frame=CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, scrollView.frame.size.height)
    image3.frame=CGRectMake( SCREEN_WIDTH*2, 0,  SCREEN_WIDTH, scrollView.frame.size.height)

  //ScrollView可以滑动的内容大小    scrollView.contentSize.width=image1.bounds.size.width*3


    scrollView.contentSize.height=scrollView.bounds.size.height

//是否允许分页
scrollView.pagingEnabled=true

    scrollView.addSubview(image1)
    scrollView.addSubview(image2)
    scrollView.addSubview(image3)



    self.view.addSubview(scrollView)

}


func pageNumberChanged(sender : AnyObject){
    //        判断如果页数为最后一页,就从头开始
    if self.pageControl.currentPage == self.pageControl.numberOfPages - 1 {
        self.pageControl.currentPage = 0
    }
        //        依次往后滚动视图
    else{
        self.pageControl.currentPage += 1
    }

    //        设置图片显示
    let page : CGFloat = (CGFloat)((self.pageControl.currentPage))
    let x = page * (self.scrollView.frame.width)
    self.scrollView.contentOffset = CGPointMake(x, 0);
}

func creatPageControl(){
    //        创建分页控制器
   self.pageControl = UIPageControl(frame: CGRectMake(150, 200, 100, 20))

    //        设置分页的页码数和当前页码
   self.pageControl.numberOfPages = 3;
   self.pageControl.currentPage = 0;

    //        设置选中页码点的颜色和未选中页码点的颜色
    self.pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
    self.pageControl.pageIndicatorTintColor = UIColor.grayColor()

    //        将分页控制器添加到滚动视图中
   self.view.addSubview(self.pageControl)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Swift实现的网络图片浏览器

博文 来自: yqh19880321

Swift 图片下拉放大

阅读数 1764

Swift 图片加水印

阅读数 117

没有更多推荐了,返回首页