iOS: обратный UIBezierPath (bezierPathWithOvalInRect)

У меня есть изображение jpg с круглым объектом в прямоугольнике, и я хочу сделать прозрачным объект круглого объекта...

Пример

(Удалите красную область в этом примере)

С помощью этого iOS делает часть UIImage прозрачной и " UIBezierPath bezierPathWithOvalInRect" у меня есть небольшой успех, но это делает путь вокруг моего объекта, и мне нужно инвертировать его, чтобы сделать прозрачным снаружи, а не внутри пути.

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

Вот мой код:

//BezierPath
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 100, 100)];  

// Create an image context containing the original UIImage.
UIGraphicsBeginImageContext(_imgTemp.image.size);
[_imgTemp.image drawAtPoint:CGPointZero];

// Clip to the bezier path and clear that portion of the image.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context,bezierPath.CGPath);
CGContextClip(context);
CGContextClearRect(context,CGRectMake(0,0,self._imgTemp.image.size.width,self._imgTemp.image.size.height));

// Build a new UIImage from the image context.
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self._imgTemp.image = newImage;

Кто-нибудь получил решение?


person Jones123    schedule 06.04.2012    source источник
comment
Вы хотите, чтобы красный стал прозрачным или черный стал прозрачным?   -  person David Rönnqvist    schedule 06.04.2012


Ответы (1)


Чтобы рисовать только внутри черного круга, вы должны переместить [_imgTemp.image drawAtPoint:CGPointZero]; после CGContextClip(context);, а затем полностью удалить вызов CGContextClearRect( ... ):

//BezierPath
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 100, 100)];  

// Create an image context containing the original UIImage.
UIGraphicsBeginImageContext(_imgTemp.image.size);

// Clip to the bezier path and clear that portion of the image.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context,bezierPath.CGPath);
CGContextClip(context);

// Draw here when the context is clipped
[_imgTemp.image drawAtPoint:CGPointZero];

// Build a new UIImage from the image context.
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self._imgTemp.image = newImage;
person David Rönnqvist    schedule 06.04.2012
comment
Можно обрезать текущий контекст в UIBezierPath с помощью [bezierPath addClip], поэтому вам не нужно напрямую возиться с CGContextRef. - person Dondragmer; 11.04.2012