在CALayer中设置图像,如UIColor

时间:2015-03-21 13:34:10

标签: ios swift calayer

我正在开发一个应用程序,当我在一层CALayer类型上绘制时,我用手指绘制的路径整体变得透明。现在我可以用平面颜色来做,但我需要的不是平面颜色,而是有图像:

enter image description here enter image description here

我用于这些的代码是:

RevealLayer.swift

import UIKit

class RevealLayer: CALayer {
        var drawingPath = UIBezierPath()
    func drawingPathMethod()->(UIBezierPath){

        drawingPath.moveToPoint(CGPointZero)
        drawingPath.lineWidth = 200.0
        drawingPath.lineCapStyle = kCGLineCapRound

        return drawingPath

    }

     override func drawInContext(ctx: CGContext!) {
        UIGraphicsPushContext(ctx)

        UIColor.grayColor().set()
        CGContextSetLineCap(ctx, kCGLineCapRound)
        CGContextFillRect(ctx, self.bounds)
        self.opacity = 0.8
        CGContextSetLineWidth(ctx, 10.0)
        CGContextSetBlendMode(ctx, kCGBlendModeClear)
        drawingPath.stroke()
        UIGraphicsPopContext()
    }

}

ViewController.swift

import UIKit
import QuartzCore

class ViewController: UIViewController {
           var path = RevealLayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.userInteractionEnabled = true
        self.view.multipleTouchEnabled = false

        var img = UIImageView(frame: view.frame)

        img.image = UIImage(named: "colour_roca_02.png")
        self.view.addSubview(img)

        path.drawingPath.lineWidth = 50.0

        path.frame = self.view.bounds

        path.setNeedsDisplay()

        self.view.layer.addSublayer(path)

    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        var touch = touches.anyObject() as UITouch
        var location = touch.locationInView(self.view)

        path.drawingPath.moveToPoint(location)
        path.setNeedsDisplay()
    }

    override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
        var touch = touches.anyObject() as UITouch
        var location = touch.locationInView(self.view)

        path.drawingPath.addLineToPoint(location)
        path.setNeedsDisplay()

    }

}

编辑:

我把这段代码:

 var imageForColor = UIImage(named: "colour_roca_01.png")       
    var imageColor = UIColor(patternImage: imageForColor!)
    imageColor.set()

这就是结果:

enter image description here

我尝试绘制Rect,这就是发生的事情:

var rect: CGRect = self.frame
        imageForColor?.drawInRect(rect)

enter image description here

编辑:这是使用不同尺寸的不同图像解决的,每个可能的屏幕尺寸都有一个。

0 个答案:

没有答案