Triangular UIView or UIImageView

后端 未结 2 1416
后悔当初
后悔当初 2020-12-23 12:02

I have requirement like below image.

\"enter

But, i\'m confused about how to a

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 12:32

    You can use UIBezierPath and CAShapeLayer to achieve this


    Step1: Copy following code

    TrImageView.swift

    import UIKit
    
    protocol TriImageViewDelegate: class {
        func didTapImage(image: UIImage)
    }
    
    class TriImageView:UIView {
    
        //assumption: view width = 2 x view height
    
        var images = [UIImage]()
    
        var delegate:TriImageViewDelegate?
    
        override func awakeFromNib() {
            super.awakeFromNib()
    
            //add imageviews
            for i in 1...3 {
                let imageView = UIImageView()
                imageView.tag = i
                imageView.userInteractionEnabled = true
                self.addSubview(imageView)
            }
    
            //add gesture recognizer
            self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(TriImageView.handleTap(_:))))
    
        }
    
        //override drawRect
        override func drawRect(rect: CGRect) {
            super.drawRect(rect)
    
            let width = rect.size.width
            let height = rect.size.height
            let frame = CGRect(x: 0, y: 0, width: width, height: height)
    
            let pointA = CGPoint(x: 0, y: 0)
            let pointB = CGPoint(x: width * 0.79, y: 0)
            let pointC = CGPoint(x: width, y: 0)
            let pointD = CGPoint(x: width * 0.534,y: height * 0.29)
            let pointE = CGPoint(x: 0, y: height * 0.88)
            let pointF = CGPoint(x: 0, y: height)
            let pointG = CGPoint(x: width * 0.874, y: height)
            let pointH = CGPoint(x: width, y: height)
    
            let path1 = [pointA,pointB,pointD,pointE]
            let path2 = [pointE,pointD,pointG,pointF]
            let path3 = [pointB,pointC,pointH,pointG,pointD]
    
            let paths = [path1,path2,path3]
    
            for i in 1...3 {
                let imageView = (self.viewWithTag(i) as! UIImageView)
                imageView.image = images[i - 1]
                imageView.frame = frame
                addMask(imageView, points: paths[i - 1])
            }
    
        }
    
        //Add mask to the imageview
        func addMask(view:UIView, points:[CGPoint]){
    
            let maskPath = UIBezierPath()
            maskPath.moveToPoint(points[0])
    
            for i in 1..


    Step2: Set the custom class


    Step3: Use it

提交回复
热议问题