Question

This is what I am trying to do: create two CGLayers, A and B. Put B over A, using a blend mode, get the resulting image.

This is the code

// Begin the drawing
CGLayerRef objectLayer;
CGContextRef fundoContext, objectContext;
CGRect backRect, objectRect;

CGFloat w = myImage.size.width;
CGFloat h = myImage.size.height;
CGSize sz = CGSizeMake(w, h);

backRect  = CGRectMake (0, 0, h, w);

UIGraphicsBeginImageContext(sz);  
CGContextRef context = UIGraphicsGetCurrentContext();
fundoLayer = CGLayerCreateWithContext (context, sz, NULL);
fundoContext = CGLayerGetContext (fundoLayer);

CGContextDrawImage(fundoContext, backRect, myImage.CGImage);
CGContextDrawLayerAtPoint(context, CGPointMake(0,0), fundoLayer);



UIImage *myObject = [[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle] 
 pathForResource:@"image" ofType:@"png"]];


w = myObject.size.width;
h = myObject.size.height;
sz = CGSizeMake(w, h);

float centroW, centroH;

// centering
objectRect  = CGRectMake (((myImage.size.width - w) / 2 ),
((myImage.size.height - h) / 2 ), w, h);

centroW = myImage.size.width / 2;
centroH = myImage.size.height / 2;


//objectRect  = CGRectMake (0, 0, h, h);
objectLayer = CGLayerCreateWithContext (context, sz, NULL);
objectContext = CGLayerGetContext (objectLayer);

// in theory this should set the blendmode of the top layer to screen…
CGContextSetBlendMode(objectContext, kCGBlendModeScreen);


CGContextDrawImage(objectContext, objectRect, myObject.CGImage);
CGContextDrawLayerAtPoint(context, CGPointMake(centroW, centroH), objectLayer);

resultingImage = UIGraphicsGetImageFromCurrentImageContext();  

the result I get is that resultingImage is not equal to the composition of the two layers. In fact resultingImage is equal just to the first layer. The second layer is being ignored by this!!!

???

am I missing something?

thanks for any help.

Was it helpful?

Solution

It looks like you're assuming myImage is larger than myObject, since you're trying to center one within the other.

When you create objectLayer, it has the smaller size - that of myObject.

The rect objectRect is positioned to center the smaller image within the larger.

But when you call CGContextDrawImage on myObject, you use objectRect to position the image within the smaller layer -- this appears to be a mismatch.

So maybe the trouble is simply that, in the last CGContextDrawImage call, objectRect is positioning the second layer out of frame.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top