[Swift]線を描く
線を描く
let image:UIImage = self.getUIImageOfVerticalGrid(self.view.frame.size, start: 0.0, lineInterval: 10.0, lineThickness: 1.0, lineColorHex: "ff0000") let iv:UIImageView = UIImageView(image:image) iv.contentMode = UIViewContentMode.ScaleAspectFit iv.frame = CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height) self.view.addSubview(iv) func getUIImageOfVerticalGrid(size:CGSize, start:CGFloat=0.0, lineInterval:CGFloat=44.0, lineThickness:CGFloat=1.0, lineColorHex:String="D6D6D6") -> UIImage { return self.getUIImageOfGrid(false, size: size, start: start, lineInterval: lineInterval, lineThickness: lineThickness, lineColorHex: lineColorHex) } func getUIImageOfGrid(horizontal:Bool, size:CGSize, start:CGFloat=0.0, lineInterval:CGFloat=44.0, lineThickness:CGFloat=1.0, lineColorHex:String="D6D6D6") -> UIImage { let scale:CGFloat = UIScreen.mainScreen().scale UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let context:CGContextRef = UIGraphicsGetCurrentContext() CGContextSetLineWidth(context, 0.0) let color:rgbTuple = self.getColorTupleByColorHex(lineColorHex) CGContextSetRGBStrokeColor(context, color.r,color.g,color.b, 1.0) CGContextSetRGBFillColor(context, color.r,color.g,color.b, 1.0) let w:CGFloat = (horizontal) ? size.width : lineThickness / scale let h:CGFloat = (horizontal) ? lineThickness / scale : size.height var currentPosition:CGFloat = start let maxPosition:CGFloat = (horizontal) ? size.height : size.width while currentPosition < maxPosition { let x:CGFloat = (horizontal) ? 0.0 : currentPosition let y:CGFloat = (horizontal) ? currentPosition : 0.0 CGContextFillRect(context, CGRectMake( x, y, w, h)) currentPosition += lineInterval } let image:UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func getColorTupleByColorHex(colorHex:String, alpha:CGFloat=1.0) -> (r:CGFloat,g:CGFloat,b:CGFloat){ let colorScanner:NSScanner = NSScanner(string: colorHex) var color:UInt32 = 0 colorScanner.scanHexInt(&color) let r:CGFloat = CGFloat((color & 0xFF0000) >> 16) / CGFloat(255.0); let g:CGFloat = CGFloat((color & 0x00FF00) >> 8) / CGFloat(255.0); let b:CGFloat = CGFloat(color & 0x0000FF) / CGFloat(255.0); return (r: r, g: g, b: b) }