Trying to create a rectangle filled with blue UIImage object - iphone

I want to create a blue rectangle image and see it in my view, but this code doesn't seem to work:
CGRect imageRect = CGRectMake(50, 50, 64, 40);
UIGraphicsBeginImageContext(imageRect.size);
[[UIColor blueColor] set];
UIRectFill(imageRect);
UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *myImageView = [[UIImageView alloc] initWithImage:aImage];
[self.view addSubview:myImageView];
Can someone fix it for me?
Thanks,
Sagiftw

Your context is 64 points by 40 points. You filled a rectangle starting 50 points from the origin in a 40-point-tall context. That put it out of bounds, and anything you draw outside the bounds of the context won't show up.
Set your rectangle's origin to 0,0, which is the origin of the context. Then, your 64×40-point rectangle will be completely within the bounds of your 64×40-point context.
If you actually want to draw the rectangle 50 points below and to the right of the context's origin, then you need to make the context's size at least big enough to hold that margin plus the size of the rectangle. If you also want the same amount of margin on the other size, then the context's size should be the rectangle's size plus 100 points wide by 100 points tall (50 points on each side of the rectangle on each axis).

Related

SpriteKit: SKShapeNode.calculateAccumulatedFrame returns a frame, which is bigger than its content

I create a SKShapeNode rectangle with a fixed size using the following code
SKShapeNode *rect = [SKShapeNode shapeNodeWithRect: CGRectMake(0, 0, 100, 200)];
CGRect accumulatedFrame = rect.calculateAccumulatedFrame;
Debugging the code above, the accumulatedFrame holds the values below:
origin=(x=-0.5, y=-0.5) size=(width=101, height=201)
Why is the calculated, accumulated frame bigger than the intended 100x200 ?
Thanks in advance for any hint :)
Code sample:
SKShapeNode *rect = [SKShapeNode shapeNodeWithRect: CGRectMake(0, 0, 200, 100)];
CGRect accumulatedFrame = rect.calculateAccumulatedFrame;
CGRect frame = rect.frame;
debugger returns origin=(x=-0.5, y=-0.5) size=(width=201, height=101) for the accumulated frame property
debugger returns origin=(x=-0.5, y=-0.5) size=(width=201, height=101) for the frame propery
Using an origin > (0,0) adds only 0,5 to width and height; seems, that sprite-kit returns an accumulated frame, which really contains the node(s) and adds 0.5, so none of the node borders intersects the border of the accumulated frame. Didn't find anything about it in the api reference...
I believe the issue you are dealing with is that if you have a strokeColor defined, that border stroke adds to size of the rectangle.
Try this code :
SKShapeNode *rect = [SKShapeNode shapeNodeWithRect: CGRectMake(0, 0, 200, 100)];
rect.strokeColor = nil;
You have to look at the stroke as being additive, and adding to the dimensions of your shape.

How does CGContextTransalateCTM work?

I am trying to draw a box/path in drawRect in one of my view's, the path rect is:
CGRect pathRect = CGRectMake(self.buttonSize_ + 25, commentYOffset, rect.size.width - 80, 40);
and before this I have:
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0.0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
I wanted this path to be drawn 100 pixels from the top, so what I did is set that commentYOffset to 100, however this doesn't do it. What am I doing wrong so that when I draw this path it starts at 100 pixels from the top?
CGContextTranslateCTM(context,…) applies a translation transform to context. The translation is applied after any existing transform in the drawing context. Those last two lines in the code you posted effectively flip the vertical on your drawing context. Just leave them out and the path will be drawn where you want.
Edit: adit says he needs the transforms to keep some text drawing right side up, so: If you need to flip the vertical on your drawing context (as you're doing) then just remember that after applying these transformations zero-y is at the bottom of rect and the positive y-axis points towards the top of rect. So to draw your path 100 pixels from the top you should make
commentYOffset = CGRectGetMaxY(rect) - 40.0 - 100.0;
and that 40 is because your rect is 40 points tall. Actually it's better practice to make these named constants so you don't have to copy magic numbers all over the place going forward. Then your code will look something like this:
commentYOffset = CGRectGetMaxY(rect) - kPathRectHeight - kPathTopMargin;

How do achieve a frame around image

I like the way this (http://shakeitphoto.com/) application puts a border around the image.. i would like to do something similar in my application but not sure how should I go about doing it.
Any ideas on how given a UIImage can I wrap a frame around it?
From that website, it appears you want a border with a shadow. There's 2 reasonable options, 3 if you don't care about the shadow.
If you don't care about the shadow, you can just do something like
#import <QuartzCore/QuartzCore.h> // this should be at the top
// inside your view layout code
myImageView.layer.borderColor = [UIColor whiteColor].CGColor
myImageView.layer.borderWidth = 5;
This will give you a 5-pixel white border inset into the view, layered on top of the view's contents (e.g. the image). What it won't give you is a shadow. If you want the shadow, there's 2 other options.
You could just create an image that includes the border and the shadow, and nothing else. Just make everything else alpha-transparent. Then you can simply layer this image on top of the one you want to display (either with 2 imageviews, or by creating a third image out of the 2). This should work fine, but it won't scale to different image sizes. In the case of the linked app, the image size is always the same so they could be using this.
The other option is to simply draw the border and shadow on top of your image in a new image. Here's a bit of sample code that will do this - it creates a new image the same size as your original, but with a white, shadowed border:
- (UIImage *)borderedImage:(UIImage *)image {
// the following NO means the new image has an alpha channel
// If you know the source image is fully-opaque, you may want to set that to YES
UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
[image drawAtPoint:CGPointZero];
CGContextRef ctx = UIGraphicsGetCurrentContext();
const CGFloat shadowRadius = 5;
CGContextSetShadowWithColor(ctx, 0, shadowRadius, [UIColor blackColor].CGColor);
[[UIColor whiteColor] set];
CGRect rect = (CGRect){CGPointZero, image.size};
const CGFloat frameWidth = 5;
rect = CGRectInset(rect, frameWidth / 2.0f, frameWidth / 2.0f);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
path.lineWidth = frameWidth;
[path stroke];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// note: getting the new image this way throws away the orientation data from the original
// You could create a third image by doing something like
// newImage = [UIImage imageWithCGImage:newImage.CGImage scale:newImage.scale orientation:image.orientation]
// but I am unsure as to how orientation actually affects rendering (if at all)
UIGraphicsEndImageContext();
return newImage;
}
(note: this code has not been compiled and could contain bugs)

CGImageCreateWithImageInRect causing distortion

I'm using CGImageCreateWithImageInRect to do a magnifying effect, and it works beautifully, except when I get close to the edges of my view. In that case, clipping causes the image to be distorted. Right now I grab a 72x72 chunk of the view, apply a round mask to it, and then draw the masked image, and a circle on top.
When the copied chunk is near the edge of the view, It winds up smaller than 72x72 because of clipping, and then when it's drawn in the magnifying glass it gets stretched out.
When the touch point is close to the left edge, for example, I would like to create an image where the left part is filled with a solid color, and the right half contains part of the view that's being magnified. Then apply the mask to that image and add the overlay on top.
Here's what I'm doing now. imageRef is the image being magnified, mask is a round mask, and overlay is a circle to mark the edges of the magnified region.
CGImageRef subImage = CGImageCreateWithImageInRect(imageRef, CGRectMake(touchPoint.x - 36, touchPoint.y - 36, 72, 72));
CGImageRef xMaskedImage = CGImageCreateWithMask(subImage, mask);
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextConcatCTM(context, xform);
CGRect area = CGRectMake(touchPoint.x - 84, -touchPoint.y, 170, 170);
CGRect area2 = CGRectMake(touchPoint.x - 80, -touchPoint.y + 4, 160, 160);
CGContextDrawImage(context, area2, xMaskedImage);
CGContextDrawImage(context, area, overlay);
I solved this by using CGBitmapContextCreate() to create a bitmap context. Then I drew the captured area into a smaller area of this context, and created an image from it with CGBitmapContextCreateImage(). That was the missing piece of the puzzle.

How to compensate the flipped coordinate system of core graphics for easy drawing?

It's really a pain, but always when I draw an UIImage in -drawRect:, it's upside-down.
When I flip the coordinates, the image draws correctly, but at the cost of all other CG functions drawing "wrong" (flipped).
What's your strategy when you have to draw images and other things? Is there any rule of thumb how to not get stuck in this problem over and over again?
Also, one nasty thing when I flip the y-axis is, that my CGRect from the UIImageView frame is wrong. Instead of the origin appearing at 10,10 upper left as expected, it appears at the bottom.
But at the same time, all those normal line drawing functions of CGContext take correct coordinates. drawing a line in -drawRect with origin 10,10 upper left, will really start at upper left. But at the same time that's strange, because core graphics actually has a flipped coordinate system with y 0 at the bottom.
So it seems like something is really inconsistent there. Drawing with CGContext functions takes coordinates as "expected" (cmon, nobody thinks in coordinates starting from bottom left, that's silly), while drawing any kind of image still works the "wrong" way.
Do you use helper methods to draw images? Or is there anything useful that makes image drawing not a pain in the butt?
Problem: Origin is at lower-left corner; positive y goes upward (negative y goes downward).
Goal: Origin at upper-left corner; positive y going downward (negative y going upward).
Solution:
Move origin up by the view's height.
Negate (multiply by -1) the y axis.
The way to do this in code is to translate up by the view bounds' height and scale by (1, -1), in that order.
There are a couple of portions of the Quartz 2D Programming Guide that are relevant to this topic, including “Drawing to a Graphics Context on iPhone OS” and the whole chapter on Transforms. Of course, you really should read the whole thing.
You can do that by apply affinetransform on the point you want to convert in UIKit related coordinates. Following is example.
// Create a affine transform object
CGAffineTransform transform = CGAffineTransformMakeScale(1, -1);
// First translate your image View according to transform
transform = CGAffineTransformTranslate(transform, 0, - imageView.bounds.size.height);
// Then whenever you want any point according to UIKit related coordinates apply this transformation on the point or rect.
// To get tranformed point
CGPoint newPointForUIKit = CGPointApplyAffineTransform(oldPointInCGKit, transform);
// To get transformed rect
CGRect newRectForUIKit = CGRectApplyAffineTransform(oldPointInCGKit, transform);
The better answer to this problem is to use the UIImage method drawInRect: to draw your image. I'm assuming you want the image to span the entire bounds of your view. This is what you'd type in your drawRect: method.
Instead of:
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIImage *myImage = [UIImage imageNamed:#"theImage.png"];
CGImageRef img = [myImage CGImage];
CGRect bounds = [self bounds];
CGContextDrawImage(ctx, bounds, img);
Write this:
UIImage *myImage = [UIImage imageNamed:#"theImage.png"];
CGRect bounds = [self bounds];
[myImage drawInRect:bounds];
It's really a pain, but always when I draw an UIImage in -drawRect:, it's upside-down.
Are you telling the UIImage to draw, or getting its CGImage and drawing that?
As noted in “Drawing to a Graphics Context on iPhone OS”, UIImages are aware of the difference in co-ordinate spaces and should draw themselves correctly without you having to flip your co-ordinate space yourself.
CGImageRef flip (CGImageRef im) {
CGSize sz = CGSizeMake(CGImageGetWidth(im), CGImageGetHeight(im));
UIGraphicsBeginImageContextWithOptions(sz, NO, 0);
CGContextDrawImage(UIGraphicsGetCurrentContext(),
CGRectMake(0, 0, sz.width, sz.height), im);
CGImageRef result = [UIGraphicsGetImageFromCurrentImageContext() CGImage];
UIGraphicsEndImageContext();
return result;
}
Call the above method using the code below:
This code deals with getting the left half of an image from an existing UIImageview and setting the thus generated image to a new imageview - imgViewleft
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextDrawImage(con,
CGRectMake(0,0,sz.width/2.0,sz.height),
flip(leftReference));
imgViewLeft = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()];