Search code examples
iosswiftuiviewcalayer

View with Custom design


Need to design single view like the attached design in swift and this to be visible at all my collecitonview cell, how to achieve this anyone have idea about this

enter image description here


Solution

  • I have tried it in a test project. This is my way:

    Open Photoshop or a similar tool and make a picture with a translucent background.

    enter image description here

    Use the PS tools to draw a figure the way you want it.

    enter image description here

    Save it as a PNG. Open Xcode. Put a UIImageView into your UIViewController. Put the PDF into your Assets folder and set this Image as the Image for the UIImageView. Set the contraints.

    enter image description here

    Set the following code into the UIViewController.swift file:

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var testImageView: UIImageView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
    
            let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
            tap.numberOfTapsRequired = 1
            view.addGestureRecognizer(tap)
        }
    
        func doubleTapped() {
    
            let image = UIImage(named: "test")
            testImageView.image =  image?.maskWithColor(color: UIColor.blue)
        }
    
    
    }
    
    extension UIImage {
        func maskWithColor(color: UIColor) -> UIImage? {
    
            let maskImage = self.cgImage
            let width = self.size.width
            let height = self.size.height
            let bounds = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: width, height: height))
    
            let colorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
            let bitmapContext = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) //needs rawValue of bitmapInfo
    
            bitmapContext!.clip(to: bounds, mask: maskImage!)
            bitmapContext!.setFillColor(color.cgColor)
            bitmapContext!.fill(bounds)
    
            //is it nil?
            if let cImage = bitmapContext!.makeImage() {
                let coloredImage = UIImage(cgImage: cImage)
    
                return coloredImage
    
            } else {
                return nil
            } 
        }
    }
    

    Start the app and touch the display. The color changes from black to blue once tapped. Now you should have all the tools to do whatever you want too... The Code is in Swift 3 language.

    enter image description hereenter image description here

    You can set this UIImageView into your UICollectionViewCell and set the UIColor with the function provided.

    And here is a function to set a random UIColor.