How to crop the image using UIBezierPath?

后端 未结 8 1661
我在风中等你
我在风中等你 2020-11-30 23:16

I want to get the image from the UIBezierpath closed path(See the image). I draw the image on the UIView using drawRect method and als

8条回答
  •  遥遥无期
    2020-11-30 23:47

    Well, there are a couple of things that you have to take in notice.

    1. Are you passing your UIImageView instead of your UIView?
    2. If you are, did you enable your image view for touch handling?
    3. Subclass your UIImageView and use drawrect() for handling that stuff for you.

    If you want only a portion of the image (like the cat), then you need to submask your image according to UIBezierPath.

    Updated

    The following is a complete working example, change it to your requirements.

    ViewController.h:

    @interface ViewController : UIViewController
    {
      UIBezierPath *aPath;
    }
    @property (nonatomic,retain) NSMutableArray *pathArray;
    @property (nonatomic,retain) NSMutableDictionary *dic;
    @property (nonatomic,retain) IBOutlet UIImageView *imgView;
    
    @end
    

    ViewController.m:

    @interface ViewController ()
     - (IBAction)Crop:(id)sender;
    @end
    
    @implementation ViewController
    @synthesize pathArray,dic,imgView;
    - (void)viewDidLoad
     {
       [super viewDidLoad];
    
     }
     - (void) setClippingPath:(UIBezierPath *)clippingPath : (UIImageView *)imgView;
    {
    
        NSLog(@"Mask Paths %@",clippingPath);
    
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.frame = self.imgView.frame;
        maskLayer.path = [clippingPath CGPath];
        maskLayer.fillColor = [[UIColor whiteColor] CGColor];
        maskLayer.backgroundColor = [[UIColor clearColor] CGColor];
    
    
        self.imgView.layer.mask = maskLayer;
    
    
    
    }
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
     {
    
       UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
       self->aPath = [[UIBezierPath alloc]init];
       [aPath moveToPoint:[mytouch locationInView:imgView]];
    
    }
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
     {
    
      UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
      [aPath addLineToPoint:[mytouch locationInView:imgView
                           ]];
    
     }
    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
     {
    
     }
    - (IBAction)Crop:(id)sender
     {
      [self setClippingPath:aPath :imgView];
     }
    

提交回复
热议问题