Created
July 5, 2016 09:03
-
-
Save juliengdt/849dafdf27dae1cd3bff76d8ac4b64f8 to your computer and use it in GitHub Desktop.
Extension for UIImage to set a dotted pattern as image source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface UIImageView (DottableImage) | |
- (void) dottedPatternFrom:(CGPoint)fromPoint to:(CGPoint)toPoint forWidth:(CGFloat)width; | |
@end | |
@implementation UIImageView (DottableImage) | |
float const DefaultDottedImageWidth = 5.0f; | |
- (void) dottedPatternFrom:(CGPoint)fromPoint to:(CGPoint)toPoint forWidth:(CGFloat)width | |
{ | |
if (CGRectContainsPoint(self.frame, fromPoint)) { | |
NSLog(@"Warning, begin point is not included in the frame of the imageView"); | |
} | |
if (CGRectContainsPoint(self.frame, toPoint)) { | |
NSLog(@"Warning, end point is not included in the frame of the imageView"); | |
} | |
UIBezierPath *path = [[UIBezierPath alloc] init]; | |
UIImage *image; | |
[path moveToPoint:fromPoint]; | |
[path addLineToPoint:toPoint]; | |
[path setLineWidth:(width > 0.0f ? width: DefaultDottedImageWidth)]; | |
CGFloat dashes[] = { path.lineWidth, path.lineWidth * 2 }; | |
[path setLineDash:dashes count:2 phase:0]; | |
[path setLineCapStyle:kCGLineCapRound]; | |
UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 2); | |
[path stroke]; | |
image = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
if (!image) { | |
NSLog(@"Error creating dotted image"); | |
} | |
[self setImage:image]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment