Question

Is it possible to draw something on a UIView, then, after the drawing is completed, resize the view to be the same size as the thing that was previously drawn?

For example, if I draw a circle on a UIView, I would like to crop the UIView to the dimensions of the circle that I just drew on the view.

UPDATE

I am looking into using a CAShapeLayer as a possible solution. Does anyone know how to convert a UIBezierPath to a CAShapeLayer then set the position of the CAShapeLayer?

I have tried:

shapeLayer.path = bezierPath.CGPath;
shapeLayer.position = CGPointMake(0, 0);

but this does not work.

Was it helpful?

Solution

Yes you can do that. Have a look at this example that will answer both your questions.

First of all you need to add a UIView called myView and attach it to an IBOutlet ivar.

Define this global values for demonstration purposes:

#define POSITION    CGPointMake(50.0,50.0)
#define SIZE        CGSizeMake(100.0,100.0)

Declare two methods, one that will draw a shape in myView and another one that will resize the view to adapt it to the drawn shape:

-(void) circle
{
    CAShapeLayer *layerData = [CAShapeLayer layer];
    layerData.fillColor = [UIColor greenColor].CGColor;

    UIBezierPath * dataPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0.0, 0.0, SIZE.width, SIZE.height)];

    layerData.path = dataPath.CGPath;
    layerData.position = CGPointMake(POSITION.x, POSITION.y);

    [myView.layer addSublayer:layerData];
}

-(void) resize
{
    ((CAShapeLayer *)[myView.layer.sublayers objectAtIndex:0]).position = CGPointMake(0.0, 0.0);
    myView.frame = CGRectMake(POSITION.x + myView.frame.origin.x , POSITION.y + myView.frame.origin.y, SIZE.width, SIZE.height);
}

Finally, in viewWillAppear: call both methods:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self circle];
    [self resize];
}

You can run the same code calling only circle and calling both methods. In both cases the drawn circle will be at the same exact position but in the second case myView has been resized to have the same size as the drawn shape.

Hope it helps.

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