Drawing multiple UIImageView's with the same ImageContext? - iphone

I want to draw 3 different images using Core Graphics, e.g. a rectangle (imageview1), a circle (imageview2) and a triangle (imageview3).
Currently, in my ViewController, my code looks like:
- (void)viewDidLoad
{
[super viewDidLoad];
// create my rectangle
UIGraphicsBeginImageContext(CGSizeMake(200, 100));
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor colorWithRed:237/255.0 green:247/255.0 blue:242/255.0 alpha:1.0] setFill];
CGContextAddRect(context, CGRectInset(CGRectMake(0.0f, 0.0f, 10, 80), 0.0f, 0.0f));
CGContextFillPath(context);
UIImage *rectangle = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// create my ImageView
UIImageView *rectangleView = [[UIImageView alloc] initWithFrame:CGRectMake(160, 40, rectangle.size.width, rectangle.size.height)];
legView.image = leg;
// add my image view to parent view
[self.view addSubview:legView];
}
So, if I want to continue creating more images, do I need to create a new context for every new image? E.g., CGContextRef context2, context3, etc etc.? It seems a bit unwieldly, but I'm a beginner so any tips appreciated!

Related

Make UiView sub class but background color show black color

I have taken a UiView subclass but it's background color is not changing
This class I am using these method
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:CGRectMake(50, 80, 200, 200)];
if (self)
{
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor darkGrayColor]setFill];
CGContextClearRect(context, rect);
CGContextSetLineWidth(context, 2.0);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
CGContextMoveToPoint(context, 1, 1);
CGContextAddLineToPoint(context, 100, 100);
CGContextStrokePath(context); // and draw
}
I am calling this class to main view controller
Newclass *obj =[[Newsclass alloc]init];
obj.backgroundColor =[UIColor redColor];
[self.view addsubview :obj];
but background color by default show black color. It is not changing
if i implemented background-color code init with frame method or
draw rect method than not changing.
if i code it
- (id)initWithCoder:(NSCoder*)aDecoder
than it's method not called
please suggest me UIview subclass black background color how to change
First of all, you should do the color part in UIView file.
if (self = [super initWithFrame:CGRectMake(220,60, 100, 300)])
{
self.backgroundColor =[UIColor greenColor];
}
how ever you don't need to do in this case... ;)
it will definitely change your background color. But what happens next is that Draw rect method is called ,your color is no more visible as the draw rect method draws a view above it (whatever you draw in that method).
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGRect rectangle = CGRectMake(0,0,200,300);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillRect(context, rectangle);
}
You just cannot directly set the background color of cgcontext, you have to fill that context with color.
please make sure that you replace rectangle by rectangular frame of your view. It works like a charm for me.

Getting the CGContextRef from a subview

I'm using UIGraphicsGetCurrentContext() to create a gradient background for a UI element, but I guess I misunderstood where the drawing was taking place. I wanted the drawing to take place on a subview, but instead it's happening in the view itself.
I think the problem is that when I use UIGraphicsGetCurrentContext(), I'm getting a CGContextRef of the view, so that's where the drawing is taking place. What I want to do is have the drawing take place on the subview, so that I can fade it in and out with other related subviews. Can this be done, or do I need to create another UIView subclass just for the background layer?
Here's a simplification of the code I'm using and my goal is to be able to fade in and out the background gradient in topBar while leaving the InterfaceControlsView view visible.
#implementation InterfaceControlsView
- (id)initWithFrame:(CGRect)frame
{
topBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, 20.0, self.frame.size.width, 45.0)];
/* etc. */
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = topBar.frame; // topBar is a subview
CGContextSaveGState(context);
CGContextAddRect(context, rect);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
/* etc. */
}
#end
To create gradient bg for subviews, you dont need to create subclass, use gradiant layers.
Hope this helps
CALayer *layer = _button.layer;
layer.borderWidth = 1.0f;
layer.borderColor = [UIColor lightGrayColor].CGColor;
CAGradientLayer *gLayer = [CAGradientLayer layer];
[gLayer setName:#"gradient"];
gLayer.frame = layer.bounds;
gLayer.colors = [NSArray arrayWithObjects:
(id)[UIColor colorWithRed:26.0/255.0 green:94.0/255.0 blue:74.0/255.0 alpha:1.0].CGColor,
(id)[UIColor colorWithRed:23.0/255.0 green:59.0/255.0 blue:37.0/255.0 alpha:1.0].CGColor,
nil];
[layer addSublayer:gLayer];

How to tint an image/show a colour?

2 things i want to do, which are related:
Show a block of any colour. So i could change that colour to something else at any time.
Tint a UIImage to be a different colour. An overlay of colour with alpha turned down could work here, but say it was an image which had a transparent background and didn't take up the full square of the image.
Any ideas?
Another option, would be to use category methods on UIImage like this...
// Tint the image, default to half transparency if given an opaque colour.
- (UIImage *)imageWithTint:(UIColor *)tintColor {
CGFloat white, alpha;
[tintColor getWhite:&white alpha:&alpha];
return [self imageWithTint:tintColor alpha:(alpha == 1.0 ? 0.5f : alpha)];
}
// Tint the image
- (UIImage *)imageWithTint:(UIColor *)tintColor alpha:(CGFloat)alpha {
// Begin drawing
CGRect aRect = CGRectMake(0.f, 0.f, self.size.width, self.size.height);
UIGraphicsBeginImageContext(aRect.size);
// Get the graphic context
CGContextRef c = UIGraphicsGetCurrentContext();
// Converting a UIImage to a CGImage flips the image,
// so apply a upside-down translation
CGContextTranslateCTM(c, 0, self.size.height);
CGContextScaleCTM(c, 1.0, -1.0);
// Draw the image
[self drawInRect:aRect];
// Set the fill color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextSetFillColorSpace(c, colorSpace);
// Set the mask to only tint non-transparent pixels
CGContextClipToMask(c, aRect, self.CGImage);
// Set the fill color
CGContextSetFillColorWithColor(c, [tintColor colorWithAlphaComponent:alpha].CGColor);
UIRectFillUsingBlendMode(aRect, kCGBlendModeColor);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Release memory
CGColorSpaceRelease(colorSpace);
return img;
}
The first one is easy. Make a new UIView and set its background color to whatever color you’d like.
The second is more difficult. As you mentioned, you can put a new view on top of it with transparency turned down, but to get it to clip in the same places, you’d want to use a mask. Something like this:
UIImage *myImage = [UIImage imageNamed:#"foo.png"];
UIImageView *originalImageView = [[UIImageView alloc] initWithImage:myImage];
[originalImageView setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[parentView addSubview:originalImageView];
UIView *overlay = [[UIView alloc] initWithFrame:[originalImageView frame]];
UIImageView *maskImageView = [[UIImageView alloc] initWithImage:myImage];
[maskImageView setFrame:[overlay bounds]];
[[overlay layer] setMask:[maskImageView layer]];
[overlay setBackgroundColor:[UIColor redColor]];
[parentView addSubview:overlay];
Keep in mind you’ll have to #import <QuartzCore/QuartzCore.h> in the implementation file.
Here is another way to implement image tinting, especially if you are already using QuartzCore for something else.
Import QuartzCore:
#import <QuartzCore/QuartzCore.h>
Create transparent CALayer and add it as a sublayer for the image you want to tint:
CALayer *sublayer = [CALayer layer];
[sublayer setBackgroundColor:[UIColor whiteColor].CGColor];
[sublayer setOpacity:0.3];
[sublayer setFrame:toBeTintedImage.frame];
[toBeTintedImage.layer addSublayer:sublayer];
Add QuartzCore to your projects Framework list (if it isn't already there), otherwise you'll get compiler errors like this:
Undefined symbols for architecture i386: "_OBJC_CLASS_$_CALayer"
An easy way to achieve 1 is to create a UILabel or even a UIView and change the backgroundColor as you like.
There is a way to multiply colours instead of just overlaying them, and that should work for 2. See this tutorial.
Try this
- (void)viewDidLoad
{
[super viewDidLoad];
UIView* maskedView = [self filledViewForPNG:[UIImage imageNamed:#"mask_effect.png"]
mask:[UIImage imageNamed:#"mask_image.png"]
maskColor:[UIColor colorWithRed:.6 green:.2 blue:.7 alpha:1]];
[self.view addSubview:maskedView];
}
-(UIView*)filledViewForPNG:(UIImage*)image mask:(UIImage*)maskImage maskColor:(UIColor*)maskColor
{
UIImageView *pngImageView = [[UIImageView alloc] initWithImage:image];
UIImageView *maskImageView = [[UIImageView alloc] initWithImage:maskImage];
CGRect bounds;
if (image) {
bounds = pngImageView.bounds;
}
else
{
bounds = maskImageView.bounds;
}
UIView* parentView = [[UIView alloc]initWithFrame:bounds];
[parentView setAutoresizesSubviews:YES];
[parentView setClipsToBounds:YES];
UIView *overlay = [[UIView alloc] initWithFrame:bounds];
[[overlay layer] setMask:[maskImageView layer]];
[overlay setBackgroundColor:maskColor];
[parentView addSubview:overlay];
[parentView addSubview:pngImageView];
return parentView;
}

how to darken a UIImageView

I need to darken a UIImageView when it gets touched, almost exactly like icons on the springboard (home screen).
Should I be added UIView with a 0.5 alpha and black background. This seems clumsy. Should I be using Layers or something (CALayers).
I would let a UIImageView handle the actual drawing of the image, but toggle the image to one that's been darkened in advance. Here's some code I've used to generate darkened images with alpha maintained:
+ (UIImage *)darkenImage:(UIImage *)image toLevel:(CGFloat)level
{
// Create a temporary view to act as a darkening layer
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
UIView *tempView = [[UIView alloc] initWithFrame:frame];
tempView.backgroundColor = [UIColor blackColor];
tempView.alpha = level;
// Draw the image into a new graphics context
UIGraphicsBeginImageContext(frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[image drawInRect:frame];
// Flip the context vertically so we can draw the dark layer via a mask that
// aligns with the image's alpha pixels (Quartz uses flipped coordinates)
CGContextTranslateCTM(context, 0, frame.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextClipToMask(context, frame, image.CGImage);
[tempView.layer renderInContext:context];
// Produce a new image from this context
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *toReturn = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
UIGraphicsEndImageContext();
[tempView release];
return toReturn;
}
How about subclassing UIView and adding a UIImage ivar (called image)? Then you could override -drawRect: something like this, provided you had a boolean ivar called pressed that was set while touched.
- (void)drawRect:(CGRect)rect
{
[image drawAtPoint:(CGPointMake(0.0, 0.0))];
// if pressed, fill rect with dark translucent color
if (pressed)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextSetRGBFillColor(ctx, 0.5, 0.5, 0.5, 0.5);
CGContextFillRect(ctx, rect);
CGContextRestoreGState(ctx);
}
}
You would want to experiment with RGBA values above. And, of course, non-rectangular shapes would require a bit more work - like a CGMutablePathRef.
UIImageView can have multiple images; you could have two versions of the image and switch to the darker one when needed.

How to style UITextView with a 3D shadowed border?

In another post, luvieere shared a means by which rounded corners can be applied to a text view using the QuartzCore framework (see post). It would seem to me that a 3D border, like that found on a UITextField, could be created via layers instead of using a background image.
Does anyone know if or how this can be done? I'd really like to find a method to add a 3D border WITHOUT having to fire up a graphics editor and create a 3D shadowed background. Thanks!
In View Controller:
newCommentBody.layer.cornerRadius = 7;
newCommentBody.clipsToBounds = YES;
Make new class TextView inherits UITextView
#import "TextView.h"
#import <CoreGraphics/CoreGraphics.h>
#import <CoreGraphics/CGColor.h>
#implementation TextView
-(void) drawRect:(CGRect)rect {
UIGraphicsBeginImageContext(self.frame.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(currentContext, 1.0); //or whatever width you want
CGContextSetRGBStrokeColor(currentContext, 0.6, 0.6, .6, 1.0);
CGRect myRect = CGContextGetClipBoundingBox(currentContext);
//printf("rect = %f,%f,%f,%f\n", myRect.origin.x, myRect.origin.y, myRect.size.width, myRect.size.height);
float myShadowColorValues[] = {0,0,0,1};
CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef colorRef = CGColorCreate(myColorSpace, myShadowColorValues);
CGContextSetShadowWithColor(currentContext, CGSizeMake(0, -1), 3, colorRef);
// CGContextSetShadow(currentContext, CGSizeMake(0, -1), 3);
CGContextStrokeRect(currentContext, myRect);
UIImage *backgroundImage = (UIImage *)UIGraphicsGetImageFromCurrentImageContext();
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
[myImageView setImage:backgroundImage];
[self addSubview:myImageView];
[backgroundImage release];
UIGraphicsEndImageContext();
}
#end
m_txtViewSource.layer.borderWidth = 1;
m_txtViewSource.layer.borderColor = [[UIColor grayColor] CGColor];
it's not 3D but it simpler and safe code