Question

I currently have a UIView and a imageview behind that: What I would like to do is be able to "cut" out STAR shape on the UIView so that the Imageview can be visible. How do you go about doing this?

Right now I'm able to cut a rectangle or a circle shape but dont know about a star or Polygon so If anyone know anything about it please share...thanx in advance

Was it helpful?

Solution

Woof

I'm pretty sure you need to use an image mask. This is an image containing only a black shape (a star in your case) on a white background. See a tutorial on how to do this here: http://iosdevelopertips.com/cocoa/how-to-mask-an-image.html

In this scenario, the UIImageView would need to be on top of the UIView then masked using the method in the above link. As far as I know, there isn't a simple way of 'cutting' a shape from a view but this method should give you the same effect.

Another option if you want more control over the shape at runtime is to draw a star as a CGShape and use that as your mask.

OTHER TIPS

Create a shape layer,

CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
    [shapeLayer setFrame:CGRectMake(10, 10, 50, 50)];
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:CGPointMake(12, 25)];
    [bezierPath addLineToPoint:CGPointMake(25, 12)];
    [bezierPath addLineToPoint:CGPointMake(38, 25)];
    [bezierPath addLineToPoint:CGPointMake(25, 38)];
    [bezierPath closePath];
    [shapeLayer setPath:bezierPath.CGPath];

Above bezier path has random point, create your own version of star and set the frame according to your star position and size.

And mask the layer to your view,

[[yourView layer] setMask:shapeLayer];

If you want to draw a star shaped image..I am pretty much sure that this piece of code would really help you.

These two lines are responsible for start and endpoints:

CGContextMoveToPoint();
CGContextAddLineToPoint();


CGContextClosePath() : is used to close the current subpath of the context's path.

- (void)drawRect:(CGRect)rect
{

    CGContextRef contextRef=UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(contextRef, 2);
    CGContextSetStrokeColorWithColor(contextRef, [UIColor redColor].CGColor);

    CGContextBeginPath(contextRef);
    CGContextMoveToPoint(contextRef, 50.0, 440.0);
    CGContextAddLineToPoint(contextRef, 100.0, 440.0);
    CGContextAddLineToPoint(contextRef, 75.0, 380.0);
    CGContextClosePath(contextRef);
    CGContextMoveToPoint(contextRef, 50.0, 400.0);
    CGContextAddLineToPoint(contextRef, 100.0, 400.0);
    CGContextAddLineToPoint(contextRef, 75.0, 460.0);
    CGContextClosePath(contextRef);
    [[UIColor grayColor]setFill];
    CGContextStrokePath(contextRef);
    CGContextFillPath(contextRef);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top