I have two rectangles (two closed sub cgpaths).
Rectangle B is small and is present inside Rectangle A. All edges within it.
Is there a direct way to fill color area external to the rectangle B.
CAShapeLayer fillExternalColor something like that? If not a direct way, how to do this programmatically?
A - Purple color
B - Yellow color
So I tried drawing A and then drawing B. I wanted B to be of clear color (for now I put Yellow) but then I see purple color of A..
I found CGRectIntersection method that gives AnB and CGRectUnion method that gives AuB.
Is there a method that gives the rest of the area which is AuB - AnB?
You are using a CAShapeLayer. If your fillColor and your strokeColor are both opaque (alpha 1.0), you can simply set the layer's backgroundColor to fill those pixels that are within the layer's bounds but outside of its stroked and filled path.
My test code:
#implementation ViewController {
CAShapeLayer *layer;
}
- (void)viewDidLoad {
[super viewDidLoad];
layer = [CAShapeLayer layer];
layer.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 250, 250)].CGPath;
layer.fillColor = [UIColor yellowColor].CGColor;
layer.strokeColor = [UIColor whiteColor].CGColor;
layer.lineWidth = 4;
layer.backgroundColor = [UIColor purpleColor].CGColor;
[self.view.layer addSublayer:layer];
}
- (void)viewDidLayoutSubviews {
layer.frame = self.view.bounds;
}
#end
Result:
I wanted to add red border inner rectangle on UIImage with masked outer part.
I came through this page. The following code is using CGContextEOFillPath can be helpful to others like me. (Some of the code is gathered from other pages.)
-(UIImage ) imageByDrawingBorderRectOnImage:(UIImage )image theRect:(CGRect)theRect
{
// begin a graphics context of sufficient size
UIGraphicsBeginImageContext(image.size);
// draw original image into the context
[image drawAtPoint:CGPointZero];
// get the context for CoreGraphics
CGContextRef ctx = UIGraphicsGetCurrentContext();
// set stroking color and to draw rect
[[UIColor redColor] setStroke];
// drawing with a red stroke color
CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
// the line width to 3
CGContextSetLineWidth(ctx, 3.0);
// Add Stroke Rectangle,
CGContextStrokeRect(ctx, theRect);
// Now draw fill outside part with partial alpha gray color
// drawing with a gray stroke color
CGMutablePathRef aPath = CGPathCreateMutable();
// outer rectangle
CGRect rectangle = CGRectMake( 0, 0, image.size.width, image.size.height);
CGPathAddRect(aPath, nil, rectangle);
// innter rectangle
CGPathAddRect(aPath, nil, theRect);
// set gray transparent color
CGContextSetFillColorWithColor(ctx, [UIColor colorWithRed:0.75 green:0.75 blue:0.75 alpha:0.5].CGColor);
// add the path to Context
CGContextAddPath(ctx, aPath);
// This method uses Even-Odd Method to draw in outer rectangle
CGContextEOFillPath(ctx);
// make image out of bitmap context
UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();
// free the context
UIGraphicsEndImageContext();
return retImage;
}
Regards.
Assuming A is the bigger shape, B is the smaller, inner shape, and bounds refers to the containing rect of A (probably the bounds of the view)
Clip shape B to the context (-addClip should do it)
CGContextClearRect the bounds
Fill shape A
Edit, found the source of this code
Given HoleView : UIView you must set:
self.opaque = NO;
self.backgroudColor = [UIColor clearColor];
and in drawRect:
[[UIColor purpleColor] setFill];
UIRectFill(A);
CGRect gapRectIntersection = CGRectIntersection(B, A);
[[UIColor clearColor] setFill];
UIRectFill(gapRectIntersection);
kCAFillRuleEvenOdd
Specifies the even-odd winding rule. Count the total number of path crossings. If the number of crossings is even, the point is outside the path. If the number of crossings is odd, the point is inside the path and the region containing it should be filled.
Available in OS X v10.6 and later.
Declared in CAShapeLayer.h.
Refer to :CAShapeLayer Class reference
Related
I have to draw an oval shape button, i don't want to set the image in oval shape.
I have read that you can draw different shaper with UIBezierPath but i am unable to draw a proper oval shape.
Here is the code is am using to create a circular shape.
self.layer.borderWidth=1.0;
self.clipsToBounds = YES;
[self setTitleColor:ktextColor forState:UIControlStateNormal];
self.layer.cornerRadius = self.bounds.size.width/2;//half of the width
self.layer.borderColor=[[UIColor whiteColor]CGColor];
Any help is appreciated !!
You can set the delegate for your button's layer and implement the delegate method `displayLayer:'
-(void)displayLayer:(CALayer *)layer
{
UIGraphicsBeginImageContext(layer.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(0.0, 0.0, CGRectGetWidth(layer.frame), CGRectGetHeight(layer.frame))];
[[UIColor whiteColor] setFill];
[ovalPath fill];
[[UIColor blackColor] setStroke];
ovalPath.lineWidth = 1;
[ovalPath stroke];
UIImage *imageBuffer = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
layer.contents = (id)[imageBuffer CGImage];
}
You can also create a CAShapelayer and than add gesture to the layer as below:
-(void)generateOvalWithSize:(CGSize)size origin:(CGPoint)origin {
CAShapeLayer ovalLayer = [CAShapeLayer layer];
CGMutablePathRef ovalPath = CGPathCreateMutable();
CGPathAddEllipseInRect(ovalPath, NULL, CGRectMake(origin.x, origin.y, size.width, size.height));
CGPathCloseSubpath(ovalPath);
ovalLayer.path = ovalPath;
// Configure the apperence of the circle
ovalLayer.fillColor = [UIColor whiteColor].CGColor;
ovalLayer.strokeColor = [UIColor whiteColor].CGColor;
ovalLayer.lineWidth = 2;
// Add to parent layer
[[self layer] addSublayer:ovalLayer];
}
i have been using these two functions for a while, i haven't come across any issues yet, but if someone sees an issue please let me know.
you can pass anything that is a subclass of UIView (ie. UIButton, UICollectionViewCell, etc.)
+ (void)setCornerRadius:(CGFloat)radius forView:(UIView*)view
{
[view.layer setCornerRadius:radius];
[view.layer setMasksToBounds:YES];
}
+ (void)setBordersForView:(UIView*)view width:(CGFloat)width color:(UIColor*)color
{
view.layer.borderColor = color.CGColor;
view.layer.borderWidth = width;
}
the above yields me the effect below in a collection view:
the collection view cell has a single button which is bound all the way around the edges (auto layout) and takes up the full height and width of the cell.
then i pass in the entire cell (or self.viewForBaseLineLayout if calling from within the cell) as the view parameter in both functions listed above.
for the radius parameter i am passing 20.0f.
(but this value will vary depending on the size the view you are passing; you just have to play around with it)
i know this post is old, but maybe it will help someone new : )
You can use the OBShapedButton class Download Here
I am trying to draw rounded corners on rectangle in drawRect method using bezier path, but somehow the rounded corner is being shown on inner side of rectangle, instead of both inner and outer sides. Code is given below. Also attached herewith is border that is currently being drawn (outer side of border is not rounded)
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context=UIGraphicsGetCurrentContext();
//Set gray color to whole context
[[UIColor lightGrayColor] set];
CGContextSetAlpha(context,0.7);
UIRectFill(rect);
// Configure the context colors and line
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:131./255. green:148./255. blue:219./255. alpha:1.0].CGColor);
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetLineWidth(context, 10.0);
CGSize size=self.bounds.size;
CGFloat radius = 10.0;
CGSize guideSize=CGSizeMake(330, 130);
CGRect guideCoords= CGRectMake(size.width*.5-guideSize.width*.5, size.height*.5-guideSize.height*.5, guideSize.width , guideSize.height);
// Guide drawing
CGContextStrokeRect(context,guideCoords);
// Draw the Text
[kVinGuideMessage drawInRect:CGRectMake(guideCoords.origin.x+kSideMessageMargin, guideCoords.origin.y+guideSize.height+kMarginFromGuide, guideCoords.size.width-2*kSideMessageMargin,40) withFont:[UIFont systemFontOfSize:16.0] lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];
//Get instersection and clear color of inner overlay
CGRect holeRectIntersection = CGRectIntersection(rect,guideCoords);
//----------ADDING ROUNDED CORNERS HERE-----------//
CGPathRef clippath = [UIBezierPath bezierPathWithRoundedRect:guideCoords cornerRadius:radius].CGPath;
CGContextAddPath(context, clippath);
CGContextClip(context);
//------------------------------------------------//
[[UIColor clearColor] setFill];
UIRectFill(holeRectIntersection);
}
The outer corners are being drawn by the CGContextStrokeRect(context,guideCoords); I think. At that point you haven't set a clipping path and your line width is 10 points, so why would the outer corners be rounded? I think you'll have better luck if you set a clipping path (probably not exactly the same clipping path you've got at the bottom) before calling stroke rect on the guideCoords rectangle.
I wondered if anyone knows how to get a shadaow effect like the one in things as per the screenshot. To me it looks like the shadow effect is created by having a shadow at the bottom of the cell above and the top of the cell below.
I can create the one from the cell above using the code below but can't figure out how to do it on the cell underneath as it doesn't get shown it's as if the cells are rendered in reverse order in terms of the z-index.
self.layer.shadowOffset = CGSizeMake(0, 2);
self.layer.shadowColor = [[UIColor blackColor] CGColor];
self.layer.shadowRadius = 2;
self.layer.shadowOpacity = 0.5;
CGFloat top = self.layer.bounds.origin.y;
CGFloat left = self.layer.bounds.origin.x;
CGFloat width = self.layer.bounds.size.width;
CGRect shadowFrame = CGRectMake(left, top, width, 44);
CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:shadowFrame].CGPath;
self.layer.shadowPath = shadowPath;
Any suggestions much appreciated.
Things http://www.purplesmash.com/images/Things.jpg
Just create hollow rectangle while drawing with CoreGraphics (align it exactly that hollow part cover your cell visible view) and set shadow for context - this will save performance for you.
UPDATE:
I've tried this inside my cell drawRect: method
// Creating path which will hold our hollow rectangle
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(-8.0f, -8.0f, 336.0f, 96.0f));
CGPathAddRect(path, NULL, CGRectMake(-5.0f, 0.0f, 330.0f, 80.0f));
// Saving current graphics context state
CGContextSaveGState(context);
// Configuring shadow
CGContextSetShadowWithColor(context, CGSizeMake(0.0f, 0.0f), 6.0f,
[[UIColor blackColor] CGColor]);
// Adding our path
CGContextAddPath(context, path);
// Configure hollow rectangle fill color
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
// Fill rectangle and keep hollow part transparent
CGContextEOFillPath(context);
// Restore graphics context
CGContextRestoreGState(context);
Of course additional improvement will be pre-calculate CGMutablePathRef path somewhere in initialization or in this method by condition if(path == NULL). Colors can be retained too. If this should be last row of your cell update, than maybe you don't event need to save context state.
You probably need to do this by drawing the shadows as part of the checked cell instead of setting the shadow properties on the surrounding cells.
I'd do it by adding one or two CAGradientLayers as children of the checked cell's contentView.layer.
I have edited this in light of the suggestion from moonlight. I put that code into a method addInnerTopShadow when a cell needs that I call the method. I have added another method addInnerBottomShadow which puts in the shadow at the bottom.
I call these methods in the drawRect method and when I want to change between the states I call the method:
[cell setNeedsDisplay];
This allows me to toggle the state of the cell without doing things like
[self.tableView reloadData];
As the methods suggest I have outer shadow methods that put a shadow on the first and last cells but that's another issue and has been answered many times. I now have my app working exactly how I want. So thanks to Rob and Moonlight.
-(void)addInnerBottomShadow
{
CGContextRef context = UIGraphicsGetCurrentContext();
// Creating path which will hold our hollow rectangle
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 44, 480, 80));
CGPathAddRect(path, NULL, CGRectMake(0, 54, 480, 96));
// Saving current graphics context state
CGContextSaveGState(context);
// Configuring shadow
CGContextSetShadowWithColor(context, CGSizeMake(0.0f, 0.0f), 6.0f, [[UIColor blackColor] CGColor]);
// Adding our path
CGContextAddPath(context, path);
// Configure hollow rectangle fill color
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
// Fill rectangle and keep hollow part transparent
CGContextEOFillPath(context);
CGContextClipToRect(context, self.bounds);
// Restore graphics context
CGContextRestoreGState(context);
}
-(void)addInnerTopShadow
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(-8.0f, -8.0f, 336.0f, 96.0f));
CGPathAddRect(path, NULL, CGRectMake(-5.0f, 0.0f, 330.0f, 80.0f));
// Saving current graphics context state
CGContextSaveGState(context);
// Configuring shadow
CGContextSetShadowWithColor(context, CGSizeMake(0.0f, 0.0f), 7.0f, [[UIColor blackColor] CGColor]);
// Adding our path
CGContextAddPath(context, path);
// Configure hollow rectangle fill color
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
// Fill rectangle and keep hollow part transparent
CGContextEOFillPath(context);
CGContextClipToRect(context, self.bounds);
// Restore graphics context
CGContextRestoreGState(context);
}
I am trying to overlay an image with some extra information: some text and rectangles. Right now I am stuck at drawing the rectangles. They just won't show up. What am I doing wrong? The image itself is being drawn, so the graphics context must be ok.
- (void)drawTag:(NSString *)tag withRect:(CGRect)rect
{
// Set the color in the current graphics context for future draw operations
[[UIColor yellowColor] setStroke];
[[UIColor yellowColor] setFill];
// Create our drawing path
UIBezierPath* drawingPath = [UIBezierPath bezierPathWithRect:rect];
// actually draw it
[drawingPath stroke];
}
- (IBAction)showDetails:(id)sender
{
// draw the image
UIGraphicsBeginImageContext(self.userImage.size);
// This one shows up:
[self.userImage drawAtPoint:CGPointZero];
// This one does not:
[self drawTag:#"Test" withRect:CGRectMake(10, 10, 50, 50)];
// Show the whole thing:
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.imageViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:self.imageViewController animated:YES];
}
You should set the lineWidth property of UIBezierPath to a value >= 1
I have a UIScrollView that contains a subview that I want to fill with a texture.
- (void)drawRect:(CGRect)rect {
CGImageRef image_to_tile_ret_ref = CGImageRetain(wood.CGImage);
CGRect tile_rect;
tile_rect.size = wood.size;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0, 0);
CGContextDrawTiledImage(context, tile_rect, image_to_tile_ret_ref);
// Something here to make it fill a big area
CGContextFillPath(context);
CGImageRelease(image_to_tile_ret_ref);
}
This just seems to fill the visible area of the scroll view and when I scroll, the rest is white. How do I draw a rectangle beyond the bounds of the rect? Is that bad?
If you want to draw a background color in this is too much. UIScrollView can have a background color. That color can be created from a patter that is an image.
You can create a pattern color
UIColor * bgColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"imgname.png"]];
scrollView.backgroundColor = bgColor;