I want to overlay a rectangle within an image. This code below currently works but it returns a rect with a thin frame. I cant change the rect frame width. One way to return a custom rect with thicker border is by using UIView but it's not possible to add a SubView to an UIImage. Any solution to this? Thank you.
-(UIImage *)drawRectangleOnImage:(UIImage *)img rect:(CGRect )rect{
CGSize imgSize = img.size;
CGFloat scale = 0;
UIGraphicsBeginImageContextWithOptions(imgSize, NO, scale);
[img drawAtPoint:CGPointZero];
[[UIColor redColor] setStroke];
UIRectFrame(rect);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
CodePudding user response:
UIRectFrame draws a frame around the inside of the specified rect. If you want to fill the area instead, you can use UIRectFill.
To change the stroke and/or fill colour, you can call -setStroke
or -setFill
on UIColor
. For example:
[[UIColor red] setFill];
UIRectFill(rect);
To set the stroke line width, you need to set the line width on the current CGContext:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 10);
Edit: There’s an even easier way: NSFrameRectWithWidth allows you to directly specify the width instead of setting the line width on the context.