iOS: двухэтапная обработка изображений с помощью CoreGraphics - PullRequest
8 голосов
/ 05 мая 2011

Используя CoreGraphics (внутри моего метода drawRect), я пытаюсь применить режим наложения к изображению (прозрачный png), а затем настроить альфа-результат результата.Я предполагаю, что это нужно сделать в два этапа, но я могу ошибаться.Вот что у меня пока есть (что отлично работает):

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);

//SET COLOR - EDIT... added a more practical color example
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1);

//flips drawing context (apparently this is necessary)
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);//flip context

//DRAW PIN IMAGE
UIImage *pin = [UIImage imageNamed:@"pin"];
CGRect pinrect = CGRectMake(12, 17, 25, 25);    
CGContextDrawImage(context, pinrect, pin.CGImage);//draws image in context

//Apply blend mode
CGContextSetBlendMode(context, kCGBlendModeColor); 
CGContextClipToMask(context, pinrect, pin.CGImage); // restricts drawing to within alpha channel

//fills context with mask, applying blend mode
CGContextFillRect(context, pinrect); 

CGContextRestoreGState(context);

// -- Do something here to make result 50% transparent ?? --

Я предполагаю, что мне нужно где-то нарисовать все это в каком-то отдельном контексте, вызвать CGContextSetAlpha(...), а затем перерисоватьэто вернулось к моему первоначальному контексту, но я не уверен как.Установка альфа до моего последнего CGContextFillRect просто изменит количество, на которое был применен режим наложения, а не альфа всего изображения.

РЕДАКТИРОВАТЬ: снимок экрана отправлен

enter image description here

Спасибо заранее.

1 Ответ

9 голосов
/ 07 мая 2011

Используя слои прозрачности, вы можете применить наложение к изображению, нарисованному на 100%, и отобразить результат на 50%.Результат выглядит следующим образом:
Image showing output Я использовал текстурированный фон, чтобы вы могли четко видеть, что нижнее изображение прозрачно для всех на 50%, а не просто для другого изображения, как было в моей предыдущей попытке.Вот код:

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);//flip context

CGRect fullImageRect = (CGRect){42,57,100,100};
CGRect transparentImageRect = (CGRect){12,17,100,100};
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1);

// Draw image at 100%
UIImage *testImage = [UIImage imageNamed:@"TestImage"];
CGContextDrawImage(context,fullImageRect,testImage.CGImage);

// Set 50% transparency and begin a transparency layer. Inside the transparency layer, the alpha is automatically reset to 1.0
CGContextSetAlpha(context,0.5);
CGContextBeginTransparencyLayer(context, NULL);
// Draw the image. It is viewed at 100% within the transparency layer and 50% outside the transparency layer.
CGContextDrawImage(context, transparentImageRect, testImage.CGImage);
// Draw blend on top of image
CGContextClipToMask(context, transparentImageRect, testImage.CGImage);
CGContextSetBlendMode(context, kCGBlendModeColor);
CGContextFillRect(context, transparentImageRect);
// Exit transparency layer, causing the image and blend to be composited at 50%.
CGContextEndTransparencyLayer(context);

Редактировать: старый контент удален, так как он занимал много места и был бесполезен.Посмотрите историю изменений, если хотите ее увидеть.

...