drawRect on top of subviews

A subview will always be drawn on “top” of its superview. Depending on your specific requirements, you may need to have a plain UIView as the background/container view, with your existing subviews in there, and then your custom view as another subview added to the very top, so it has the highest Z-order. This would … Read more

UIView transparent gradient

This was an embarrassingly easy fix: apply a CAGradientLayer as my subview’s mask. CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = _fileTypeScrollView.bounds; gradientLayer.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor, nil]; gradientLayer.startPoint = CGPointMake(0.8f, 1.0f); gradientLayer.endPoint = CGPointMake(1.0f, 1.0f); _fileTypeScrollView.layer.mask = gradientLayer; Thanks to Cocoanetics for pointing me in the right direction!

Draw a simple circle uiimage

Thanks for the Q&A! Swift code as below: extension UIImage { class func circle(diameter: CGFloat, color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSizeMake(diameter, diameter), false, 0) let ctx = UIGraphicsGetCurrentContext() CGContextSaveGState(ctx) let rect = CGRectMake(0, 0, diameter, diameter) CGContextSetFillColorWithColor(ctx, color.CGColor) CGContextFillEllipseInRect(ctx, rect) CGContextRestoreGState(ctx) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } } Swift 3 version provided by … Read more

How to fill a path with gradient in drawRect:?

I would clip to the path you want to fill, and use CGContextDrawLinearGradient. Here is a simple implementation of drawRect: as an example: – (void) drawRect:(CGRect)rect { // Create a gradient from white to red CGFloat colors [] = { 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0 }; CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient … Read more

How to make a dashed line in swift?

Swift 4 @IBOutlet var dashedView: UIView! func drawDottedLine(start p0: CGPoint, end p1: CGPoint, view: UIView) { let shapeLayer = CAShapeLayer() shapeLayer.strokeColor = UIColor.lightGray.cgColor shapeLayer.lineWidth = 1 shapeLayer.lineDashPattern = [7, 3] // 7 is the length of dash, 3 is length of the gap. let path = CGMutablePath() path.addLines(between: [p0, p1]) shapeLayer.path = path view.layer.addSublayer(shapeLayer) } … Read more