查看定制设计

时间:2016-09-23 07:05:30

标签: ios swift uiview calayer

需要像swift中的附加设计一样设计单个视图,这在我的所有collecitonview单元格中都可见,如何实现这一点任何人都对此有所了解

enter image description here

1 个答案:

答案 0 :(得分:2)

我在测试项目中尝试过它。这是我的方式:

打开Photoshop或类似工具,制作半透明背景的照片。

enter image description here

使用PS工具以您希望的方式绘制图形。

enter image description here

将其另存为 PNG 。打开Xcode。将UIImageView放入UIViewController。将PDF放入Assets文件夹并将此Image设置为UIImageView的图像。设置约束。

enter image description here

将以下代码设置到UIViewController.swift文件中:

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
        } 
    }
}

启动应用并触摸显示屏。一旦轻敲,颜色从黑色变为蓝色。现在你应该拥有所有你想做的工具......代码是用Swift 3语言编写的。

enter image description here enter image description here

您可以将此UIImageView设置为UICollectionViewCell,并使用提供的功能设置UIColor。

And here is a function to set a random UIColor.