1

我有一个 DrawView UIView,它可以让你在现有的 UIImageView 上进行手绘。这是我用来绘制 DrawView 的代码:

class DrawView: UIView {

/* Variables */
var lines: [Line] = []
var lastPoint: CGPoint!

var actionsCountArr:[Int] = []


required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
}


override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    lastPoint = touches.anyObject()?.locationInView(self)

}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    var newPoint = touches.anyObject()?.locationInView(self)

    lines.append(Line(start: lastPoint, end: newPoint!))
    lastPoint = newPoint
    self.setNeedsDisplay()
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    actionsCountArr.append(lines.count)
    println("actions: \(actionsCountArr)")

}
// Draw Rect function
override func drawRect(rect: CGRect) {
    var context = UIGraphicsGetCurrentContext()
    CGContextBeginPath(context)
    for line in lines {
        CGContextMoveToPoint(context, line.start.x, line.start.y)
        CGContextAddLineToPoint(context, line.end.x, line.end.y)
        CGContextSetStrokeColorWithColor(context, colorPicked?.CGColor)
        CGContextSetLineWidth(context, lineWidth!)
        CGContextSetLineCap(context, kCGLineCapRound)
        CGContextStrokePath(context)
    }
}   

}

class Line {
        var start: CGPoint
        var end: CGPoint

    init(start _start: CGPoint, end _end: CGPoint) {
        start = _start
        end = _end
    }
}

然后这是我用来将此类 UIView 的绘制线渲染为 UIImage 的方法(它位于另一个在背景中也有 UIImageView 的类中):

func renderDrawingViewImage() {
    var rect:CGRect = drawingView.bounds
    UIGraphicsBeginImageContextWithOptions(rect.size, true, 0.0)
    drawingView.drawViewHierarchyInRect(drawingView.bounds, afterScreenUpdates: false)
    drawingImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

// Call the Filtering method
    applyPixellateFilter()
    }

之后,我在该drawingImage上应用 CIPixellate 过滤器,我得到的结果是我的 drawingImage 获得了过滤器并且看起来像素化,但是该图像的整个背景变黑,不透明,就像它在开始时一样(DrawView 有bkg 颜色设置为 clearColor)。

这是代码:

func applyPixellateFilter() {
// Apply Pixllate filter to the drawing
var CIfilterName = "CIPixellate"

let ciContext = CIContext(options: nil)
let coreImage = CIImage(image: drawingImage)
let filter = CIFilter(name: CIfilterName)
filter.setDefaults()

filter.setValue(CIVector(x: 150, y: 150), forKey: kCIInputCenterKey)
filter.setValue(10.0, forKey: kCIInputScaleKey)

// Finalize the filtered image ==========
filter.setValue(coreImage, forKey: kCIInputImageKey)
let filteredImageData = filter.valueForKey(kCIOutputImageKey) as CIImage
    let filteredImageRef = ciContext.createCGImage(filteredImageData, fromRect: filteredImageData.extent())
    drawingImage = UIImage(CGImage: filteredImageRef);
}

所以我的问题是:如何从 DrawView UIView 中获得透明的 UIImage?似乎如果我不应用那个 Pixellate 过滤器,我可以将我的背景图像与绘图视图合并,并获得具有透明背景的最后一个,但是如果我应用那个过滤器,drawingImage的背景就会变成全黑。

提前致谢!

4

0 回答 0