走进swift首页投稿(暂停使用,暂停投稿)iOS

swift代码实现群聊缩略图的自定义控件

2016-02-25  本文已影响292人  brzhang

背景介绍

效果图.png

比如要实现上图所示的这样一种效果,我们可以做一个自定义控件,该自定义控件构造方法接受3个参数。
1、控件的宽度
2、控件的高度
3、群聊中人的图片数组

最终实现效果

最终效果.gif

设计思路

1、我们可以用一个UIView来放图片,分为4种情况来处理:

case 1 : 只有一张图片
    直接用一个UIimageView填充整个UIView
case 2 : 有两张图片
    分为左上角一个,有下角一个,主要是frame的计算。
case 3: 有三张图片
    分为上面一个居中,左下角一个,有下角一个,也是主要是frame的计算
case 4: 有四张图片
    四个角落各一个

2、另外圆角处理:
UIView 都的layer中有一个cornerRadius的属性,这个直接就加圆角了,比android方便很多,圆角的borderWidth以及borderColor都很方便。

2、然后,图片之间还存在叠加的处理:
思路就是,我们虽然等分了这个UIView为4块,但是我们估计把每块的宽高,都稍微加一点,并且保证它们的frame都落在我们这个UIView之内就OK。

代码实现

//
//  CompoundImageView.swift
//  Created by brzhang on 16/2/24.
//  Copyright © 2016年 brang. All rights reserved.
//

import UIKit

class GroupCirCleImage: UIView {

    var borderWidth: CGFloat = 1.5
    var borderColor = UIColor.greenColor()
    var imageWidth: CGFloat
    var imageHeight: CGFloat
    var imageUrls : [String]?
    var ctx: CGContextRef?
    var imageCoverPx: CGFloat = 10
    lazy var sdManger = SDWebImageManager.sharedManager()
    var frames: [String: CGRect] = [String: CGRect]()
    var countFlag = 0
    init(width: CGFloat, height: CGFloat, imageUrls: [String]?) {
        imageWidth = width / 2
        imageHeight = width / 2
        self.imageUrls = imageUrls
        super.init(frame: CGRectMake(0, 0, width, height))
        drawImages()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func drawRect(rect: CGRect) {
        // Drawing code
        super.drawRect(rect)
    }

    func initFrames() {
        frames["topLeft"] = CGRectMake(0, 0, imageWidth + imageCoverPx, imageCoverPx + imageHeight)
        frames["topRight"] = CGRectMake(imageWidth - imageCoverPx, 0, imageWidth + imageCoverPx, imageCoverPx + imageHeight)
        frames["bottomLeft"] = CGRectMake(0, imageHeight - imageCoverPx, imageWidth + imageCoverPx, imageCoverPx + imageHeight)
        frames["bottomRight"] = CGRectMake(imageWidth - imageCoverPx, imageHeight - imageCoverPx, imageWidth + imageCoverPx, imageCoverPx + imageHeight)
        frames["topCenter"] = CGRectMake(self.center.x - (imageWidth + imageCoverPx) / 2, 0, imageWidth + imageCoverPx, imageCoverPx + imageHeight)
    }

    func init_context(size: CGSize) -> CGContextRef? {
        UIGraphicsBeginImageContext(size);
        let ctx = UIGraphicsGetCurrentContext()

        // 设置笔触颜色
        CGContextSetStrokeColorWithColor(ctx, borderColor.CGColor)

        // 设置笔触宽度
        CGContextSetLineWidth(ctx, borderWidth)

        // 设置填充色

        CGContextSetFillColorWithColor(ctx, UIColor.purpleColor().CGColor)

        CGContextSetLineJoin(ctx, .Round)

        CGContextSetLineCap(ctx, .Round)

        return ctx
    }

    func drawImages() {

        initFrames()

        guard imageUrls != nil && imageUrls?.count > 0 else {
            return
        }
        let count = imageUrls!.count
        switch count {
        case 1:
            // 画图
            getImageFromNet(imageUrls![0], completion: { [unowned self](result) -> Void in
                guard let image = result as? UIImage else {
                    return
                }
                let ctx = self.init_context(self.frame.size)
                let borderRect = CGRectMake(self.borderWidth / 2, self.borderWidth / 2, self.imageWidth * 2 - self.borderWidth, self.imageHeight * 2 - self.borderWidth)
                CGContextAddEllipseInRect(ctx, borderRect)
                CGContextStrokePath(ctx)

                let rect = CGRectMake(self.borderWidth, self.borderWidth, self.imageWidth * 2 - self.borderWidth * 2, self.imageHeight * 2 - self.borderWidth * 2)
                CGContextAddEllipseInRect(ctx, rect);
                // 裁剪(按照当前的路径形状裁剪)
                CGContextClip(ctx)
                image.drawInRect(rect)

                let newImage = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                self.addSubview(UIImageView.init(image: newImage))
            })
        case 2:
            countFlag = 2
            getImageFromNet(imageUrls![0], completion: { [unowned self](result) -> Void in

                self.addToView(result, frame: self.frames["topLeft"], layerPosition: 2 - 0)
            })
            getImageFromNet(imageUrls![1], completion: { [unowned self](result) -> Void in
                self.addToView(result, frame: self.frames["bottomRight"], layerPosition: 2 - 1)
            })
        case 3:
            countFlag = 3
            getImageFromNet(imageUrls![0], completion: { [unowned self](result) -> Void in

                self.addToView(result, frame: self.frames["topCenter"], layerPosition: 3 - 0)
            })
            getImageFromNet(imageUrls![1], completion: { [unowned self](result) -> Void in
                self.addToView(result, frame: self.frames["bottomRight"], layerPosition: 3 - 1)
            })
            getImageFromNet(imageUrls![2], completion: { [unowned self](result) -> Void in
                self.addToView(result, frame: self.frames["bottomLeft"], layerPosition: 3 - 2)
            })

        case 4:
            countFlag = 4

            let startTime = NSDate().timeIntervalSince1970
            hlog("start point is \(startTime)")
            getImageFromNet(imageUrls![0], completion: { [unowned self](result) -> Void in

                self.addToView(result, frame: self.frames["topLeft"], layerPosition: 4 - 0)
            })
            getImageFromNet(imageUrls![1], completion: { [unowned self](result) -> Void in

                self.addToView(result, frame: self.frames["topRight"], layerPosition: 4 - 1)
            })
            getImageFromNet(imageUrls![2], completion: { [unowned self](result) -> Void in
                self.addToView(result, frame: self.frames["bottomRight"], layerPosition: 4 - 2)
            })

            getImageFromNet(imageUrls![3], completion: { [unowned self](result) -> Void in
                self.addToView(result, frame: self.frames["bottomLeft"], layerPosition: 4 - 3)
            })
            hlog("end point is \(NSDate().timeIntervalSince1970) ,it takes \(NSDate().timeIntervalSince1970 - startTime)")
        default:
            break
        }
    }

    func addToView(result: AnyObject, frame: CGRect?, layerPosition: Int) {
        let newImage = self.generateNewImages(result)
        let uiimage = UIImageView.init(image: newImage)
        uiimage.frame = frame!
        uiimage.tag = layerPosition
        uiimage.hidden = true
        self.addSubview(uiimage)
        self.countFlag--
        if countFlag <= 0 {
            adjustLayerPosition()
        }
    }

    /**
     重新排序,覆盖方式,层级越大,越在上层,注意,view本身的tag是0
     */
    func adjustLayerPosition() {
        for i in Range(start: 1, end: 5) {
            let view = self.viewWithTag(i)
            if view != nil {
                view!.removeFromSuperview()
                view?.hidden = false
                self.insertSubview(view!, atIndex: i - 1)
            }
        }
    }

    func generateNewImages(result: AnyObject) -> UIImage? {
        guard let image = result as? UIImage else {
            return nil
        }
        let ctx = self.init_context(CGSizeMake(self.imageWidth + self.imageCoverPx, self.imageHeight + self.imageCoverPx))
        let borderRect = CGRectMake(self.borderWidth / 2, self.borderWidth / 2, self.imageWidth + self.imageCoverPx - self.borderWidth, self.imageHeight + self.imageCoverPx - self.borderWidth)
        CGContextAddEllipseInRect(ctx, borderRect)
        CGContextStrokePath(ctx)

        let rect = CGRectMake(self.borderWidth, self.borderWidth, self.imageWidth + self.imageCoverPx - self.borderWidth * 2, self.imageHeight + self.imageCoverPx - self.borderWidth * 2)
        CGContextAddEllipseInRect(ctx, rect);
        // 裁剪(按照当前的路径形状裁剪)
        CGContextClip(ctx)
        image.drawInRect(rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage
    }

    func getImageFromNet(imageUrl: String, completion: blockOne) {
        sdManger.downloadImageWithURL(NSURL.init(string: imageUrl), options: SDWebImageOptions.AllowInvalidSSLCertificates, progress: nil, completed: { (image, error, cacheType, flag, nsurl) -> Void in
            if error == nil {
                completion(result: image)
            }
        })
    }
}

extension GroupCirCleImage: ValueChangeDelete {

    func imageCoverPxChange(newConverPx: CGFloat) {
        imageCoverPx = newConverPx
        for imageview in self.subviews {
            imageview.removeFromSuperview()
        }
        drawImages()
    }
    func imageWidthChange(newWidth: CGFloat) {
    }
    func imageHeightChange(newHeight: CGFloat) {
    }
}

测试用例

import UIKit
@objc class ForTestViewController: CPBaseViewController {

    override func viewDidLoad() {
        initAndLayoutStaticViews()
    }

    override func initAndLayoutStaticViews() {

        let imageUrls = ["http://cross.store.qq.com/cross/8b44fd266bba50be97436a2cc567b7818a1d32388ee2b623/",
            "http://cross.store.qq.com/cross/ec257a55c6090677a34dcd383b86915959f138f1b9e19e1f/",
            "http://cross.store.qq.com/cross/747b4f18548187c7b720c3ea81ed5d118328e67688ee32d3/",
            "http://q2.qlogo.cn/g?b=qq&k=KX81eH22t530OorJdVqPpA&s=100&t=1416830863"]

        let view = CompoundImageView.init(width: 200, height: 200, imageUrls: imageUrls)
        //let view = GroupCirCleImage.init(width: 200, height: 200, imageUrls: imageUrls)
        view.tag = 1000
        view.frame.origin.x = SCREEN_WIDTH / 2 - 200 / 2
        view.frame.origin.y = SCREEN_HEIGHT / 2 - 200 / 2
        self.view.addSubview(view)

        let sliderImageCover = UISlider.init(frame: CGRectMake(SCREEN_WIDTH / 2 - 100 / 2, CGRectGetMaxY(view.frame) + 20, 100, 20))
        sliderImageCover.minimumValue = 5
        sliderImageCover.maximumValue = 40
        sliderImageCover.addTarget(self, action: "sliderValueChanged:", forControlEvents: .ValueChanged)
        sliderImageCover.value = 10
        self.view.addSubview(sliderImageCover)

        let labelImageCover = UILabel.init(frame: CGRectMake(CGRectGetMinX(sliderImageCover.frame) - 110, sliderImageCover.center.y - 30 / 2, 100, 30))
        labelImageCover.text = "覆盖像素:"
        self.view.addSubview(labelImageCover)

        let sizeWidthSlider = UISlider.init(frame: CGRectMake(SCREEN_WIDTH / 2 - 100 / 2, CGRectGetMaxY(sliderImageCover.frame) + 20, 100, 20))
        sizeWidthSlider.minimumValue = 100
        sizeWidthSlider.maximumValue = 300
        sizeWidthSlider.addTarget(self, action: "sizeWidthSliderValueChanged:", forControlEvents: .ValueChanged)
        sizeWidthSlider.value = 200
        self.view.addSubview(sizeWidthSlider)

        let labelImageWidth = UILabel.init(frame: CGRectMake(CGRectGetMinX(sizeWidthSlider.frame) - 110, sizeWidthSlider.center.y - 30 / 2, 100, 30))
        labelImageWidth.text = "宽度"
        self.view.addSubview(labelImageWidth)

        let sizeHeightSlider = UISlider.init(frame: CGRectMake(SCREEN_WIDTH / 2 - 100 / 2, CGRectGetMaxY(sizeWidthSlider.frame) + 20, 100, 20))
        sizeHeightSlider.minimumValue = 100
        sizeHeightSlider.maximumValue = 300
        sizeHeightSlider.addTarget(self, action: "sizeHeightSliderValueChanged:", forControlEvents: .ValueChanged)
        sizeHeightSlider.value = 200
        self.view.addSubview(sizeHeightSlider)

        let labelImageHeight = UILabel.init(frame: CGRectMake(CGRectGetMinX(sizeWidthSlider.frame) - 110, sizeHeightSlider.center.y - 30 / 2, 100, 30))
        labelImageHeight.text = "高度"
        self.view.addSubview(labelImageHeight)
    }

    func sliderValueChanged(slider: UISlider) {
        let view: ValueChangeDelete = self.view.superview?.viewWithTag(1000) as! ValueChangeDelete
        print(slider.value)
        let startTime = NSDate().timeIntervalSince1970
        hlog("start point is \(startTime)")
        view.imageCoverPxChange(CGFloat(slider.value))
        hlog("end point is \(NSDate().timeIntervalSince1970) ,it takes \(NSDate().timeIntervalSince1970 - startTime)")
    }

    func sizeWidthSliderValueChanged(slider: UISlider) {
        let view: ValueChangeDelete = self.view.superview?.viewWithTag(1000) as! ValueChangeDelete
        print(slider.value)
        view.imageWidthChange(CGFloat(slider.value))
    }
    func sizeHeightSliderValueChanged(slider: UISlider) {
        let view: ValueChangeDelete = self.view.superview?.viewWithTag(1000) as! ValueChangeDelete
        print(slider.value)
        view.imageHeightChange(CGFloat(slider.value))
    }
}

总结及问题部分

1、总结,我们在做项目的过程中,会遇到一些需求中要用到的一些ui元素是我们现有的控件无法满足的,这时候,我们有必要自己做一些自定义控件,方便代码重用。
2、问题部分来了,呵呵~~

上一篇下一篇

猜你喜欢

热点阅读