Frage

I am using the following code to draw a UIBezierPath on a UIImageView in a UIView. But it is not showing a green path.

- (void)drawRect:(CGRect)rect
{
    [[UIColor blackColor] setStroke];
    [aPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{    
    UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
    self->aPath = [[UIBezierPath alloc]init];

    CAShapeLayer* greenPath = [CAShapeLayer layer];
    greenPath.path = aPath.CGPath;
    [greenPath setFillColor:[UIColor greenColor].CGColor];
    [greenPath setStrokeColor:[UIColor blueColor].CGColor];
    greenPath.frame=CGRectMake(0, 0,100,30);

    //add shape layer to view's layer
    [[imgView layer] addSublayer:greenPath];

    aPath.lineCapStyle=kCGLineCapRound;
    aPath.miterLimit=0;
    aPath.lineWidth=10;

    [aPath moveToPoint:[mytouch locationInView:imgView]];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
    [aPath addLineToPoint:[mytouch locationInView:imgView]];
    [imgView setNeedsDisplay];
}

I need to show a green line wherever the UIBezierPath is drawn.

War es hilfreich?

Lösung

There's a lot of weird stuff going on in your code, but it runs, the problem is here

[imgView setNeedsDisplay];

As I see in your code, you want it to work on drawRect, but drawRect will only get called on setNeedsDisplay on the current view, not on imgView, switch it for

[self setNeedsDisplay];

And it will work. You'd probably need to subclass UIImageView to handle drawRect inside of it. Also, I'm guessing that you want to actually modify the image, hence the attempt to draw within in, try reading on working with CoreGraphics in an image context.

About the other issues

The main problem as I see it, is that you're confusing CALayers and CoreGraphics, as it stands right now, the CALayer you're adding to the imageView is completely unused. Just with the drawRect and setting the BezierPath as you move around should work.

Also, be careful when using ->, understand what you're getting yourself into, I usually suggest sticking to @property, and using self.myVar and _myVar.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top