我有一个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的背景全黑了。
提前致谢!