Getting the CGContextRef from a subview - iphone

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];

Related

Drawing multiple UIImageView's with the same ImageContext?

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!

UIView Animations of custom view lagging

I created a UIView Subclass and are using drawing rounded rects with UIBezierpath and fill it with some gradient.
In short this is what the subclass draw rect looks like:
CGRect frame1 = //size of Frame 1
CGRect frame2 = //size of Frame 2
//gradientingStart
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
if (options == false) {
self.color = [self createRandomColor];
}
NSArray *gradientColors = [NSArray arrayWithObjects:
(id)[UIColor colorWithHue:color saturation:saturationVal brightness:brightnessVal alpha:1].CGColor,
(id)[UIColor colorWithHue:color+0.04 saturation:saturationVal+0.15 brightness:brightnessVal-0.15 alpha:1].CGColor, nil];
CGFloat gradientLocations2[] = {0.25,1};
CGGradientRef gradient2 = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations2);
CGContextSaveGState(context);
//gradientingEnd
UIBezierPath *result =
[UIBezierPath bezierPathWithRoundedRect: frame1 cornerRadius:radius];
[result appendPath:
[UIBezierPath bezierPathWithRoundedRect: frame2 cornerRadius:radius]];
[result setLineWidth:3];
[[UIColor blackColor]setStroke];
[result stroke];
[result fill];
[result addClip];
CGContextDrawLinearGradient(context, gradient2, CGPointMake(0, 0), CGPointMake(0, self.bounds.size.height), 0);
//important to prevent leaks
CGGradientRelease(gradient2);
CGColorSpaceRelease(colorSpace);
//-------
UIImage *texture = [UIImage imageNamed:#"texture2.png"];
[texture drawInRect:CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, self.bounds.size.height)];
Now I'm creating several instances of this in my view controller and trying the move them with animations like this:
[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
costumview.alpha = 0;
[costumview setFrame:CGRectMake(320,0,320,420)];
[self reorderViewsFrom:costumview.intValue];
overlay.alpha = 0;
}completion:^(BOOL finished){
}];
But unfortunately the animation is on a device very laggy and the more (5-10) costum views are display the worse it gets.
How can i improve the performance and provide smooth animations? I think changing the costum view is not an alternative because this would destroy the sense of the application. Are there any faster ways to animate the costum view?
Your drawRect method is very intense. Drawing those gradients and rounded edges are performance heavy routines, and because your changing the frame of your image in the animation, your drawRect is getting called very often.
I would add an NSLog inside your draw rect and see how many times it gets called when you animate your custom view. You might be surprised.
You could try using:
view.layer.shouldRasterize = YES
This way you render a bitmap of the custom view before you animate it. After animating the frame change again, you should invoke drawRect again and disable shouldRasterize.
Read more about shouldRasterize here:
https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CALayer_class/Introduction/Introduction.html#//apple_ref/occ/instp/CALayer/shouldRasterize
I pointed out that using some CALayer transformation (rounding corners) causing the lag - unfournately this wasn't in the snippet I posted.
I avoided it by creating the rounded corners with a own uiview subclass. This makes the app a lot smoother. All these rasterization stuff didn't do it for me...

how to draw Arc in viewdidload method in iPhone

i try to draw arc in view i use this code.
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect rect = CGRectMake(0,0,340,480);
UIView *ui = [[UIView alloc] initWithFrame:rect];
[self.view addSubview:ui];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddArc(context, 50, 50, 20, 0, 30, 0);
//set the fill or stroke color
CGContextSetRGBFillColor(context, 0.5, 0.5, 0.5, 1.0);
CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1.0);
//fill or draw the path
CGContextDrawPath(context, kCGPathStroke);
CGContextDrawPath(context, kCGPathFill);
}
if possible to draw arc in viewdidload method kindly guide me.
Your views should be drawing when requested (e.g. in drawRect:), rather than your view controllers drawing when loaded.
So what you may want to try is creating a UIView subclass and moving the drawing code to its drawRect:.
Very briefly:
#interface MONView : UIView
#end
#implementation MONView
- (void)drawRect:(CGRect)frame
{
CGContextRef context = UIGraphicsGetCurrentContext();
<-- now draw here -->
}
#end
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect rect = CGRectMake(0,0,340,480);
UIView * ui = [[MONView alloc] initWithFrame:rect];
[self.view addSubview:ui];
[ui release];
}
It is not possible to draw an arc in view Did Load.
What you need to do is:-
1.)Add a file of type UIView(lets say ArcView.h and ArcView.m)in your project
2.)In ArcView.m file implement - (void)drawRect:(CGRect)rect method
3.)In this method you need to write your logic of drawing an arc or whatever you want to draw)
4.)Now the ViewController in which you have to show your arc lets say(ArcViewController is the file in which you want to show your arc)
5.)In ArcViewController.m file you need to do following steps:-
a.)#import "ArcView.h"
b.)Whenever you want to show your arc view do:-
ArcView *vw = [[ArcView alloc] initWithFrame:*your required frame where you want to show arc*];
vw.backgroundColor=[UIColor redColor];
[self.view addSubview:vw];
[vw release];
After that you will see your arc coming on your screen.

Adding shadow to a UINavigationControllerer

I'm trying to add shadow to a UINavigationController. My have is based on NavController and i'm trying to add a shadow like in game centers. I have this so far. It works n a UINavigationnBar but i'm trying to get it to work throughout the entire app.
CGColorRef darkColor = [[UIColor blackColor] colorWithAlphaComponent:.5f].CGColor;
CGColorRef lightColor = [UIColor clearColor].CGColor;
CAGradientLayer *newShadow = [[[CAGradientLayer alloc] init] autorelease];
newShadow.frame = CGRectMake(0, 44, 320, 10);
newShadow.colors = [NSArray arrayWithObjects:(id)darkColor, (id)lightColor, nil];
CALayer *superlayer = self.newShadow.superlayer;
[self.newShadow removeFromSuperlayer];
[superlayer addSublayer:self.newShadow];
[self.navigationBar.layer addSublayer:superlayer];
It works directly on a UINavigationBar but applying to a NavigationController project it fails. It builds but won't add the shadow. Any ideas?
EDIT:
I have been trying different approaches to this. I successfully created the gradient by using a shape.
#implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
UIImage *backgroundImage;
backgroundImage = [UIImage imageNamed:#"nav.png"];
[backgroundImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB();
size_t num_locations = 2;
CGFloat locations[2] = { 1.0, 0.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.5 };
CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations);
CGPoint myStartPoint, myEndPoint;
myStartPoint.x = 0.0;
myStartPoint.y = 0.0;
myEndPoint.x = 0.0;
myEndPoint.y = 54.0;
CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 1);
}
I can't get the gradient below the UINavigationBar and its overlaying the image. I can't seem to get this to work. What i'm trying to do is add the same shadow Game Center has. I have tried a few different ways. All I need to do here is get this to lie underneath the UINavigationBar allowing the image to be on top and have a little part of the shadow lie on top on the UITableView so when you scroll up its above the UITableView. If you fire up Game Center you'll see exactly what i'm talking about.
I believe you should add it to the
UINavigationController.view.layer
As the UINavigationController he is not a UIView child.
if already you did so, an other way to effect the navigationbar, consistently all over the app is to use the UINavigationBarCategory:
you sould pace this at the end of your delegate - after the #end
#implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
//implement your design
}
#end
EDIT
in this link you can find basic info on how to draw the bar:
An iPhone Graphics Drawing Tutorial using Quartz 2D
and here you can find how to add a shadow:adding shadow with quartz 2d
Good luck
You could subclass UIView and use your existing code to draw the shadow by overriding -drawRect:. Then wherever its needed, create it and add it to the view of the navigation controller.
Consider this example
CGFloat screenWidth = [UIScreen mainScreen].applicationFrame.size.width;
ShadowView *shadowView = [[ShadowView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, screenWidth, 20.0f)];
[self.navigationController.view insertSubview:shadowView atIndex:0];
By adding it to the view of the navigationController at index 0, you're effectively overlaying it on top of whatever the view controller is displaying. You could further improve this by checking for the scale of the main screen to appropriately calculate the height of the shadow view so that it will appear correctly on all devices regardless of having a retina display.

Drawing a transparent circle on top of a UIImage - iPhone SDK

I am having a lot of trouble trying to find out how to draw a transparent circle on top of a UIImage within my UIImageView. Google-ing gives me clues, but I still can't find a working example.
Are there any examples that anyone knows of that demonstrate this?
Easiest way is simply to create a semi-transparent square UIView, then set the cornerRadius of its layer to be half of its width/height. Something like:
UIView *squareView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
squareView.alpha = 0.5;
squareView.layer.cornerRadius = 50;
...
[squareView release];
This has got to be the simplest solution:
CGFloat r = 150;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1.5*r,1.5*r)];
lbl.text = #"●";
lbl.transform = CGAffineTransformMakeTranslation(0.0f, -r/6);
lbl.textAlignment = UITextAlignmentCenter;
lbl.backgroundColor = [UIColor clearColor];
lbl.textColor = [UIColor redColor];
lbl.font = [UIFont systemFontOfSize:2*r];
lbl.alpha = 0.5;
lbl.center = self.view.center;
[self.view addSubview:lbl];
One way would be to add a CAShapeLayer with a circular path, either directly to the layer of the UIImageView or as the layer of a new UIView that is added to the UIImageView.
If you actually want to modify the image, then create a mutable copy of it by drawing it into a CGBitmapContext then creating a new image from the modified bitmap.
CGPathRef circlePath = CGPathCreateMutable();
CGPathAddEllipseInRect( circlePath , NULL , CGRectMake( 0,0,20,20 ) );
CAShapeLayer *circle = [[CAShapeLayer alloc] init];
circle.path = circlePath;
circle.opacity = 0.5;
[myImageView.layer addSublayer:circle];
CGPathRelease( circlePath );
[circle release];
You can implement a custom sub-class of UIView that draws your image and then the circle in the drawRect method:
#interface CircleImageView : UIView {
UIImage * m_image;
CGRect m_viewRect;
// anything else you need in this view?
}
Implementation of drawRect:
- (void)drawRect:(CGRect)rect {
// first draw the image
[m_image drawInRect:m_viewRect blendMode:kCGBlendModeNormal alpha:1.0];
// then use quartz to draw the circle
CGContextRef context = UIGraphicsGetCurrentContext ()
// stroke and fill black with a 0.5 alpha
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 0.5);
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.5);
// now draw the circle
CGContextFillEllipseInRect (context, m_viewRect);
}
You will need to set up the m_viewRect and m_image member functions on init.