2013-12-16 1 views
1

У меня проблема с моим кодом, потому что я не понимаю, как обрезать изображение с помощью UIBezierPath. Я рисую один вид формы для перемещения для обрезки на одном изображении. MyViewController имеет 2 изображения и один квадрат. Имеются оригиналыImageView и croppedImageView (результат при обрезании). Я хочу переместить свой квадрат в любое место для обрезки оригиналаImageView, чтобы показать в croppedImageView мою форму.Как обрезать изображение с помощью другой формы с помощью UIBezierPath

enter image description here

После того как я двигаю квадратную форму на originalImageView как изображение below.Then я нажимаю на урожай.

enter image description here

Но результат на croppedImageView показали неправильное изображение, как это.

enter image description here

Я подробно опишу мой код:

В SquareView.m

#import "SquareView.h" 
    #import <QuartzCore/QuartzCore.h> 
    @interface SquareView() 
    { 
     UIBezierPath *aPath; 
     UILabel *textLabel; 
    } 

    @end 
    @implementation SquareView 

    - (id)initWithFrame:(CGRect)frame 
    { 
     self = [super initWithFrame:frame]; 
     if (self) { 
       self.backgroundColor = [UIColor clearColor]; 
       self.opaque = NO; 
       CGRect labelRect = CGRectMake(self.frame.size.width/2 - 30, self.frame.size.height/2 - 10, 150, 20); 
       textLabel = [[UILabel alloc] initWithFrame:labelRect]; 
       [textLabel setBackgroundColor:[UIColor clearColor]]; 
     } 
     return self; 
    } 


    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
    { 
     UITouch *aTouch = [touches anyObject]; 
     CGPoint location = [aTouch locationInView:self]; 
     CGPoint previousLocation = [aTouch previousLocationInView:self]; 
     self.frame = CGRectOffset(self.frame, location.x-previousLocation.x, location.y- previousLocation.y); 
     [textLabel setText:@"Click To Crop"]; 
     [textLabel setTextColor:[UIColor greenColor]]; 
     [self addSubview:textLabel]; 
    } 

    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
    { 
     [textLabel removeFromSuperview]; 
    } 


    - (void)drawRect:(CGRect)rect 
    { 
     aPath = [UIBezierPath bezierPath]; 
     // Start Point and Draw the lines. 
     [aPath moveToPoint:CGPointMake(0,0)]; 
     [aPath addLineToPoint:CGPointMake(300,0)]; 
     [aPath addLineToPoint:CGPointMake(300, 300)]; 
     [aPath addLineToPoint:CGPointMake(0, 300)]; 
     [aPath closePath]; 

     //Fill Color and Line Color 
     UIColor *colorBg = [UIColor clearColor]; 
     UIColor *lineColor = [UIColor redColor]; 
     [aPath setLineWidth:5]; 
     [lineColor setStroke]; 
     [aPath stroke]; 
     [colorBg setFill]; 
     [aPath fill]; 

    } 
    @end 

В MyViewController.m

 -(void)initSquareView 
    { 
      sqaure = [[SquareView alloc] initWithFrame:CGRectMake(100, 200, 300, 300)]; 

      tapeGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cropImage:)]; 
      tapeGesture.numberOfTapsRequired = 1; 

      [sqaure addGestureRecognizer:tapeGesture]; 
      [sqaure addGestureRecognizer:pinchGesture]; 
      [self.view addSubview:sqaure]; 
    } 

    -(void)cropImage:(UITapGestureRecognizer *)gesture 
    { 

      [sqaure removeFromSuperview]; 

      UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0); 
      CGContextRef context_ = UIGraphicsGetCurrentContext(); 

      //(if iOS 7), (else iOS 6) 
      if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) 
       [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:NO]; 
      else 
       [self.view.layer renderInContext:context_]; 
      UIImage *captureImage = UIGraphicsGetImageFromCurrentImageContext(); 
      UIGraphicsEndImageContext(); 

      CGRect imageRect = CGRectMake(0, 0, sqaure.frame.size.width, sqaure.frame.size.height); 
      UIGraphicsBeginImageContextWithOptions(sqaure.bounds.size, NO, 0.0f); 
      //Capture as square shape 
      //My problem is here 
      UIBezierPath *sqaurepath = [UIBezierPath bezierPath]; 
      [sqaurepath moveToPoint:CGPointMake(0,0)]; 
      [sqaurepath addLineToPoint:CGPointMake(300,0)]; 
      [sqaurepath addLineToPoint:CGPointMake(300, 300)]; 
      [sqaurepath addLineToPoint:CGPointMake(0, 300)]; 
      [sqaurepath closePath]; 
      [sqaurepath addClip]; 

      [captureImage drawInRect:imageRect]; 
      UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext(); 
      UIGraphicsEndImageContext(); 

      [self.captureImageView setContentMode:UIViewContentModeScaleAspectFit]; 
      [self.captureImageView setImage:croppedImage]; 
      [self.captureImageView setUserInteractionEnabled:YES]; 
      [[self.captureImageView layer] setBorderColor:[UIColor redColor].CGColor]; 
      [[self.captureImageView layer] setBorderWidth:3];; 

    } 
    @end 

Пожалуйста, помогите мне решить эту проблему.

+0

Почему ты рисуешь весь взгляд в контексте? Вы должны вычислять прямоугольник и чертеж, который прячется от изображения в контексте. – Wain

+0

Какую часть вы имеете в виду? – Sovannarith

+0

'self.view drawViewHierarchyInRect' и' self.view.layer renderInContext'. Это привлекает весь взгляд. Вы просто хотите часть изображения ... – Wain

ответ

0

Ваш captureImage был получен из контекста всего представления. Затем вы рисуете его в другом контексте с меньшим размером, равным размеру вашего квадрата, а затем получите тот же образ, который называется croppedImage. Это именно то, что вы имеете на последнем снимке экрана, и это ваша ошибка.

Я на самом деле не работал с кадрирование с помощью bezierPath, но если вам нужно только прямоугольной формы обнажениях вы можете использовать гораздо проще способ сделать это: Cropping an UIImage