Mirroring CIImage/NSImage - objective-c

Currently I have the following
CIImage *img = [CIImage imageWithCVImageBuffer: imageBuffer];
NSCIImageRep *imageRep = [NSCIImageRep imageRepWithCIImage:img];
NSImage *image = [[[NSImage alloc] initWithSize: [imageRep size]] autorelease];
[image addRepresentation:imageRep];
This works perfectly, I can use the NSImage and when written to a file the image is exactly how I need it to be.
However, I'm pulling this image from the users iSight using QTKit, so I need to be able to flip this image across the y axis.
My first thought was to transform the CIImage using something like this, however my final image always comes out completely blank. When written to a file the dimensions are correct but it's seemingly empty.
- (CIImage *)flipImage:(CIImage *)image
{
return [image imageByApplyingTransform:CGAffineTransformMakeScale(-1, 1)];
}
Am I approaching this the wrong way? Or have I made a mistake in my code?

That transform flips it, but the axis around which it flips is not at the center of the image, but at the left edge. You must also translate the image by its width to account for the movement caused during the scale.

Here is some code that may help someone out ==>
CGAffineTransform rotTrans = CGAffineTransformMakeRotation(M_PI_2);
CGAffineTransform transTrans1 = CGAffineTransformTranslate(rotTrans, 0.0f, 320.0f);
CGAffineTransform scaleTrans = CGAffineTransformScale(transTrans1, 1.0, -1.0);
CGAffineTransform transTrans2 = CGAffineTransformTranslate(scaleTrans, -0.0f, -320.0f);
self.view.transform = transTrans2;
I use it to flip frames from the front camera horizontally so they always appear up no matter what the rotation of the device. This stuff does get kind of tricky. One thing to do to help figure out what is going on is scaling down along either of the axes and seeing what the result is.

Related

Rotate NSImage around its vertical axis

I am trying to rotate the NSImage around the vertical axis, saving the result. The main purpose is to generate an array of frames of the same image with different rotation degrees. I need to have that array to modify each frame separately. The desired result for a single frame is the following:
So far I was trying to use CATransform3DRotate to make a single rotated NSImage, but I am not able to apply this transform to NSImage in any way. I tried applying CATransform3DRotate to a newly created CALayer and even to a layer of a specially created view, the best I can get is the same picture, as before.
CATransform3D t = CATransform3DRotate(CATransform3DIdentity, (60 * M_PI / 180), 0, 1, 0);
CALayer *layer = [CALayer layer];
[layer setFrame: imageRect];
[layer setContents:image];
[layer setTransform:t];
NSImage * newImage = [[NSImage alloc] initWithSize:layer.bounds.size];
[newImage lockFocus];
[layer renderInContext:[NSGraphicsContext currentContext].CGContext];
[newImage unlockFocus];
This code results in newImage being the same non-rotated image. I tried some other ways too, but none of them succeed.
Maybe there is an easier way to achieve my aim (generate the array of rotation frames of the same NSImage), but I have no idea, what it is.
NSImage object cannot be rotated. You need to rotate a view or layer and then save the contents of the view/layer as an image.
See Saving an NSView to a png file? for how to save a view as image.

Down-scaling an UIImage

I am having problems with resizing of my JPEG picture.
I would like it to be the size of the original picture, but instead it covers up the whole screen. I was trying myImageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"Cube Tile.jpeg"]
myImageView.contentMode = UIViewContentModeScaleAspectFit;
This is what happened:
My simulator screen gets covered with my image, but the height is slightly smaller.
I also tried adding this: myImageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"Cube Tile.jpeg"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]];
This is what happened:
My simulator screen gets covered with tiny versions of my image.
Is it possible doing this without too many lines of code?
Excuse me if I am a bit vaque.
Note 1: The original picture is 24 x 24 pixels
Note 2: I am a new developer, so I was just experimenting.
Thanks in advance, Marnix.
Have you tried setting the frame on the image view? e.g.,
float x = 0.0;
float y = 0.0;
[myImageView setFrame:CGRectMake(x,y,24,24)];
(and to make sure it's not trying to autosize based on a setting in the .xib)
[myImageView setAutoresizingMask:UIViewAutoresizingNone];
You could change the value of
myImageView.contentMode = UIViewContentModeScaleAspectFit;
to one of these Values:
typedef enum {
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit,
UIViewContentModeScaleAspectFill,
UIViewContentModeRedraw,
UIViewContentModeCenter,
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
} UIViewContentMode;
See more at the official documentation http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html

Divide UIImage into two parts along a UIBezierPath

How to divide this UIImage by the black line into two parts. The upper contour set of UIBezierPath.
I need to get two resulting UIImages. So is it possible?
The following set of routines create versions of a UIImage with either only the content inside a path, or only content outside that path.
Both make use of the compositeImage method, which uses CGBlendMode. CGBlendMode is very powerful for masking anything you can draw against anything else you can draw. Calling compositeImage: with other blend modes can have interesting (if not always useful) effects. See the CGContext Reference for all the modes.
The clipping method I described in my comment to your OP does work and is probably faster, but only if you have UIBezierPaths defining all the regions you want to clip.
- (UIImage*) compositeImage:(UIImage*) sourceImage onPath:(UIBezierPath*) path usingBlendMode:(CGBlendMode) blend;
{
// Create a new image of the same size as the source.
UIGraphicsBeginImageContext([sourceImage size]);
// First draw an opaque path...
[path fill];
// ...then composite with the image.
[sourceImage drawAtPoint:CGPointZero blendMode:blend alpha:1.0];
// With drawing complete, store the composited image for later use.
UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
// Graphics contexts must be ended manually.
UIGraphicsEndImageContext();
return maskedImage;
}
- (UIImage*) maskImage:(UIImage*) sourceImage toAreaInsidePath:(UIBezierPath*) maskPath;
{
return [self compositeImage:sourceImage onPath:maskPath usingBlendMode:kCGBlendModeSourceIn];
}
- (UIImage*) maskImage:(UIImage*) sourceImage toAreaOutsidePath:(UIBezierPath*) maskPath;
{
return [self compositeImage:sourceImage onPath:maskPath usingBlendMode:kCGBlendModeSourceOut];
}
I tested clipping, and in a few different tests it was 25% slower than masking to achieve the same result as the [maskImage: toAreaInsidePath:] method in my other answer. For completeness I include it here, but please don't use it without a good reason.
- (UIImage*) clipImage:(UIImage*) sourceImage toPath:(UIBezierPath*) path;
{
// Create a new image of the same size as the source.
UIGraphicsBeginImageContext([sourceImage size]);
// Clipping means drawing only happens within the path.
[path addClip];
// Draw the image to the context.
[sourceImage drawAtPoint:CGPointZero];
// With drawing complete, store the composited image for later use.
UIImage *clippedImage = UIGraphicsGetImageFromCurrentImageContext();
// Graphics contexts must be ended manually.
UIGraphicsEndImageContext();
return clippedImage;
}
This can be done but it requires some trigonometry. Let's consider the case for the upper image. First, determine the bottommost end point of the UIBezierPath and use UIGraphicsBeginImageContext to get the top part of the image above the line. This will look as follows:
Now, assuming that your line is straight, move pixel by pixel along the line drawing vertical strokes of clearColor (loop for top portion. Proceed on similar lines for bottom portion):
for(int currentPixel_x=0;currentPixel_x<your_ui_image_top.size.width)
UIGraphicsBeginImageContext(your_ui_image_top.size);
[your_ui_image_top drawInRect:CGRectMake(0, 0, your_ui_image_top.size.width, your_ui_image_top.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 1.0);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeClear);
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(),[UIColor clearColor].CGColor);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), currentPixel_x, m*currentPixel_x + c);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPixel_x, your_ui_image_top.size.height);
CGContextStrokePath(UIGraphicsGetCurrentContext());
your_ui_image_top = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
Your UIBezierPath will have to be converted to a straight line of the form y = m*x + c. The x in this equation will be currentPixel_x above. Iterate through the width of the image, increasingcurrentPixel_x by 1 each time. next_y_point_on_your_line will be calculated as:
next_y_point_on_your_line = m*currentPixel_x + c
Each vertical stroke will be 1 pixel wide and its height will depend on how you traverse through them. After some iterations, your image will look roughly (please excuse my poor photo-editing skills!) like:
There are multiple ways of how you draw the clear strokes and this is just one way of going about it. You can also have clear strokes that are parallel to the given path if it gives better results.
Another way is to set the alpha of the pixels below the line to 0.

CALayer Audio Indicator with Mask

Ok, What I want to do is create an audio indicator, basically overlay a mask or layer onto an image with a background color and opacity... so it looks like a red level indicator is bouncing up and down overtop of a microphone image, I got this to work in a very poor way updating the image each time with a UIImage mask but this was very inefficient.
Im trying to get it to work now with a CALayer which it does and better than the first trial and error way I tried. The problem now is Im only showing a rectangle and the corresponding level with it. I want it to be bounded by the microphone image, so it looks half full for instance, when I mask to bounds the rectangle takes the shape of the microphone and jumps up and down in that shape instead of "filling" the image.
Hopefully this isn't too confusing, I hope you can understand the premise and help!! Here is some code I have working now, in the wrong way:
self.image = [UIImage imageNamed:#"img_icon_microphone.png"];
CALayer *maskLayer = [CALayer layer];
maskLayer.frame = CGRectMake(0.f, 0.f, 200.f, 200.f);
maskLayer.contents = (id) [UIImage imageNamed:#"img_icon_microphone.png"].CGImage;
micUpdateLayer = [CALayer layer];
micUpdateLayer.frame = CGRectMake(0.f, 200.f, 200.f, -5.f);
micUpdateLayer.backgroundColor = [UIColor redColor].CGColor;
micUpdateLayer.opacity = 0.5f;
[self.layer addSublayer:micUpdateLayer];
Im then just using a NSTimer and a call to a function which simply updates the micUpdateLayer.frame y to make it appear to be moving with the audio input.
Thank you for any suggestions!

ios: Screenshot doesn't display mask Layer

I have a view with a certain background color. I am masking this view with the following code:
UIView *colorableView = [[UIView* alloc] init];
colorableView.backgroundColor = someColor;
CALayer *maskLayer = [CALayer layer];
maskLayer.contents = (id)[UIImage imageNamed:maskImageName].CGImage;
colorableView.layer.mask = maskLayer;
Ok everything works fine there. The view gets masked, so some parts are transparent. Now I make a screenshot of this view:
CGRect frame = colorableView.frame;
UIGraphicsBeginImageContext(frame.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(someUninterestingCodeToGetACorrectPosition);
[self.view.layer renderInContext:c];
UIImage *screenShotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return screenShotImage;
Taking a screenshot works (actually I display some other stuff above the view too and that gets displayed in the screenshot as well), but somehow, the mask is not recognized. Meaning what I get is a screenshot of a fully colored view (a rectangle) without the mask hiding some parts of it.
I guess ´UIGraphicsGetImageFromCurrentImageContext()`doesn't work with mask layers, so what can I do about it? I need to have a UIImage to display the screenshot in a mail.
Thanks a lot in advance
One way to fix this can be to use Quartz functions to clip the view (CGContextClip, I don't remember exactly, you'll have to dig a little bit into the documentation).
Hope this will help