CGContextAddEllipseInRect для CGImageRef для CGImageMaskСоздать для CGContextClipToMask - PullRequest
0 голосов
/ 21 июля 2011

Я не смог найти ни одного примера в интернете, который учит меня, как создать круг на лету, а затем использовать этот круг, чтобы обрезать UIImage.

Вот мой код, к сожалению, он не дает желаемых результатов.

//create a graphics context
UIGraphicsBeginImageContext(CGSizeMake(243, 243));
CGContextRef context = UIGraphicsGetCurrentContext();

//create my object in this context
CGContextAddEllipseInRect(context, CGRectMake(0, 0, 243, 243));
CGContextSetFillColor(context, CGColorGetComponents([[UIColor whiteColor] CGColor]));
CGContextFillPath(context);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//create an uiimage from the ellipse


//Get the drawing image
CGImageRef maskImage = [image CGImage];

// Get the mask from the image
CGImageRef maskRef = CGImageMaskCreate(CGImageGetWidth(maskImage)
                                    , CGImageGetHeight(maskImage)
                                    , CGImageGetBitsPerComponent(maskImage)
                                    , CGImageGetBitsPerPixel(maskImage)
                                    , CGImageGetBytesPerRow(maskImage)
                                    ,  CGImageGetDataProvider(maskImage)
                                    , NULL
                                    , false);


//finally clip the context to the mask.

CGContextClipToMask( context , CGRectMake(0, 0, 243, 243) , maskRef );


//draw the image
[firstPieceView.image drawInRect:CGRectMake(0, 0, 320, 480)];
// [firstPieceView drawRect:CGRectMake(0, 0, 320, 480)];

//extract a new image
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();

NSLog(@"self.firstPieceView is %@", NSStringFromCGRect(self.firstPieceView.frame));
UIGraphicsEndImageContext();


self.firstPieceView.image = outputImage;

Буду признателен за любые указания.

1 Ответ

4 голосов
/ 21 июля 2011

Я подозреваю, что вам нужно перефразировать ваш вопрос лучше. Существует множество примеров кода для всего, что вы пытаетесь сделать.

Вот как можно реализовать пользовательский подкласс UIView для обрезки изображения в эллипсе:

- (void)drawInRect:(CGRect)rect {
  UIImage image;// set/get from somewhere
  CGImageRef imageRef = [image CGImageRef];
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextAddEllipseInRect(context, self.bounds);
  CGContextClip(context);
  CGContextDrawImage(context, self.bounds, imageRef);
}

caveat emptor


Редактировать (через день, свободное время выдает):

- (void)drawRect:(CGRect)rect {
  // we're ignoring rect and drawing the whole view
  CGImageRef imageRef = [_image CGImage]; // ivar: UIImage *_image;
  CGContextRef context = UIGraphicsGetCurrentContext();

  // set the background to black
  [[UIColor blackColor] setFill];
  CGContextFillRect(context, self.bounds);


  // modify the context coordinates,
  // UIKit and CoreGraphics are oriented differently
  CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, CGRectGetHeight(rect));
    CGContextScaleCTM(context, 1, -1);

    // add clipping path to the context, then execute the clip
    // this is in effect for all drawing until GState restored
    CGContextAddEllipseInRect(context, self.bounds);
    CGContextClip(context);

    // stretch the image to be the size of the view
    CGContextDrawImage(context, self.bounds, imageRef);
  CGContextRestoreGState(context);
}
...