简体   繁体   中英

UIImageView draw in rect with size of image and not image view

I want to draw on UIImageView , following is my code for drawing. My image view mode is aspect fit. When i draw using the following code, since i am using drawinrect and giving the rect of UIImageView so all the images are scaled down to the size to the `imageview. I want to draw the image of size of image and not image view.Since i am detecting the touch point on the imageview so the point of tap and actual drawing on image is different. Can any body tell me how to draw on image directly. and how to calculate this shift or difference in the point of touch on image rather than image view.

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {

    UITouch *touch = [touches anyObject];
    lastTouch = [touch locationInView:self];

 }

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

CGPoint   currentTouch = [[touches anyObject] locationInView:self];

UIGraphicsBeginImageContext(self.image.size);
CGContextRef context = UIGraphicsGetCurrentContext();

[self.image drawInRect:CGRectMake(0, 0, self.image.size.width, self.bounds.size.height)];

CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, _brushSize);

CGContextBeginPath(context) ;

CGContextMoveToPoint(context, lastTouch.x, lastTouch.y);
CGContextAddLineToPoint(context,currentTouch.x,currentTouch.y) ;

CGContextSetAlpha( context , 1 );

CGContextSetStrokeColorWithColor(context, [_brushColor CGColor]);

CGContextStrokePath(context) ;

self.image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

lastTouch = currentTouch;


 }

You shouldn't really be us classing UIImageView . It isn't intended to be subclassed.

A better approach to this would be to have a UIView instead of the UIImageView .

Then two possible ways is to either...

Draw the UIImage directly into the UIView inside drawRect but this will give you the same problem that you are currently having.

Or...

In the UIView have a UIImageView . Resize this so that it is the correct size/shape for the UIImage . (Ie do the scaling yourself) then over the UIImageView put a second UIView (and subclass this) this second one will be capped DrawingView or something. You can now do all your drawing inside here. And all your touch detection will be in here too. So you no longer need to convert the touch points into different drawing points.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM