1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| import UIKit
class maskImage: UIView { private var imageSource:CGImageRef! private var customMaskImage:CGImageRef = UIImage(named: "mask2.png")!.CGImage private var maskBlack:CGImageRef = UIImage(named: "maskblack.png")!.CGImage http://stackoverflow.com/questions/24339145/how-do-i-write-a-custom-init-for-a-uiview-subclass-in-swift The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init(coder:) version will be called. Since Swift now requires an implementation of the required init(coder:), I have updated the example below and changed the let variable declarations to var and optional. In this case, you would initialize them in awakeFromNib() or at some later time. */ init(frame: CGRect,image:CGImageRef) { super.init(frame: frame) imageSource = image } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) imageSource = UIImage(named: "images.jpeg")?.CGImage } override func drawRect(rect: CGRect) { UIGraphicsBeginImageContext(self.frame.size) var imageContext = UIGraphicsGetCurrentContext() CGContextDrawImage(imageContext, CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height), maskBlack) CGContextSetRGBStrokeColor(imageContext, 1, 1, 1, 1) CGContextSetLineWidth(imageContext, 20) CGContextAddPath(imageContext, path) CGContextStrokePath(imageContext) var maskImage:CGImageRef = CGBitmapContextCreateImage(imageContext) UIGraphicsEndImageContext() var context = UIGraphicsGetCurrentContext() CGContextSaveGState(context) CGContextTranslateCTM(context, 0,self.frame.height) CGContextScaleCTM(context, 1, -1) var mask:CGImageRef = CGImageMaskCreate(CGImageGetWidth(maskImage), CGImageGetHeight(maskImage), CGImageGetBitsPerComponent(maskImage), CGImageGetBitsPerPixel(maskImage), CGImageGetBytesPerRow(maskImage), CGImageGetDataProvider(maskImage), nil, true); var newImageContent = CGImageCreateWithMask(customMaskImage, mask) 4. CGContextDrawImage(context, CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height), imageSource) CGContextDrawImage(context, CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height), newImageContent) CGContextRestoreGState(context) } var path = CGPathCreateMutable() override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { var p = (touches.first as! UITouch).locationInView(self) CGPathMoveToPoint(path, nil, p.x, p.y) } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { var p = (touches.first as! UITouch).locationInView(self) CGPathAddLineToPoint(path, nil, p.x, p.y) setNeedsDisplay() } }
|