ios - CALayer 不在轮廓处绘制

标签 ios swift swift3 calayer catiledlayer

我正在尝试在 CATileLayer 之上绘制一个 CALayer。基本上,当用户点击图 block 层时,我想用 CALayer 更新 View 。它没有在预期的地方绘制:

这是 CATileLayer 的类,它在 Storyboard 上有一个 View

class SquareView: UIView {

    override class var layerClass: AnyClass {
        return CATiledLayer.self
    }

    required init?(coder aDecoder: NSCoder ) {
        super.init(coder: aDecoder)
        guard let layer = self.layer as? CATiledLayer else { return nil }
        layer.contentsScale = 40.0
        layer.tileSize = CGSize(width: 40.0, height: 40.0)
    }

    override func draw(_ rect: CGRect) {

        let context = UIGraphicsGetCurrentContext()
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())

        context?.setFillColor(red: red, green: green, blue: blue, alpha: 1.0)
        context?.fill(rect)
    }

这是在 0.0, 0.0 处绘制的下一层,我不确定为什么它没有覆盖所需的正方形。

    override func viewDidLoad() {
        super.viewDidLoad()

        let theSelector : Selector = #selector(ViewController.tapGesture)
        let tapGesture = UITapGestureRecognizer(target: self, action: theSelector)
        tapGesture.numberOfTapsRequired = 1
        view.addGestureRecognizer(tapGesture)

    }

    func tapGesture(sender: UITapGestureRecognizer) {
        let theLayer = CALayer()

        let location = sender.location(in: inputView)
        let xInView = location.x
        let yInView = location.y


        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())

        theLayer.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0).cgColor

        theLayer.bounds = CGRect(x: xInView, y: yInView, width: 40.0, height: 40.0)



        view.layer.addSublayer(theLayer)
     }

最佳答案

结果边界默认为 0.0, 0.0。因此,最好使用 hittest 属性,或者 touches begind 函数来处理这种情况。

关于ios - CALayer 不在轮廓处绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41237907/

相关文章:

ios - 如何在不同的 iOS 设备上为 UINavigationBar 设置背景图片

ios - png数据返回UIImage

ios - Swift tvOS - 当用户按下 MENU 按钮时暂停 UIImage 动画

ios - 使用 RSBarcodes 扫描条形码时执行操作

ios - NSTimer Countdown - updateCounter Swift 3.0 新语法?

ios - 如何限制同一张照片在 iOS 的自定义相册中再次添加?

iphone - iphone 中的舍入值

ios - 在 AppSync 中获取 "Software caused connection abort"

ios - 类在两者中都实现,将使用两者之一。哪个是未定义的

c# - 将 C# 函数转换为 Swift 4.2