UINavigationBar gradient details - iphone

I'm trying to recreate the look of a UINavigationBar. The background of the bar is drawn using a gradient, but it's unclear exactly what the default colors and points are in it. Has anyone done anything in this area?

From one of my projects. Adjust the colors to your liking. It also can show a background image if you want (imageReady), else it draws the navbar like Apple's
// #Lighter r,g,b,a #Darker r,g,b,a
#define MAIN_COLOR_COMPONENTS { 0.153, 0.306, 0.553, 1.0, 0.122, 0.247, 0.482, 1.0 }
#define LIGHT_COLOR_COMPONENTS { 0.478, 0.573, 0.725, 1.0, 0.216, 0.357, 0.584, 1.0 }
#implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
if (imageReady) {
UIImage *img = [UIImage imageNamed: #"navigation_background.png"];
[img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
} else {
// Render yourself instead.
// You will need to adjust the MAIN_COLOR_COMPONENTS and LIGHT_COLOR_COMPONENTS to match your app
// emulate the tint colored bar
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat locations[2] = { 0.0, 1.0 };
CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB();
CGFloat topComponents[8] = LIGHT_COLOR_COMPONENTS;
CGGradientRef topGradient = CGGradientCreateWithColorComponents(myColorspace, topComponents, locations, 2);
CGContextDrawLinearGradient(context, topGradient, CGPointMake(0, 0), CGPointMake(0,self.frame.size.height/2), 0);
CGGradientRelease(topGradient);
CGFloat botComponents[8] = MAIN_COLOR_COMPONENTS;
CGGradientRef botGradient = CGGradientCreateWithColorComponents(myColorspace, botComponents, locations, 2);
CGContextDrawLinearGradient(context, botGradient,
CGPointMake(0,self.frame.size.height/2), CGPointMake(0, self.frame.size.height), 0);
CGGradientRelease(botGradient);
CGColorSpaceRelease(myColorspace);
// top Line
CGContextSetRGBStrokeColor(context, 1, 1, 1, 1.0);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, self.frame.size.width, 0);
CGContextStrokePath(context);
// bottom line
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1.0);
CGContextMoveToPoint(context, 0, self.frame.size.height);
CGContextAddLineToPoint(context, self.frame.size.width, self.frame.size.height);
CGContextStrokePath(context);
}
}
#end

Related

How to draw a full circle with image

I'm pretty new with core graphics. I need to draw a full circle. How do I go about it? I currently have a masked circle.
I referred to this example.
//Use the draw rect to draw the Background, the Circle and the Handle
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
CGContextRef ctx = UIGraphicsGetCurrentContext();
/** Draw the Background **/
//Create the path
CGContextAddArc(ctx, self.frame.size.width/2, self.frame.size.height/2, radius, 0, M_PI *2, 0);
// CGContextFillEllipseInRect(ctx, CGRectMake(self.frame.size.height/2, self.frame.size.width/2, 100, 100));
// CGContextSetRGBFillColor(ctx, 0.5, 0.5, 0.5, 1.0);
//Set the stroke color to black
[[UIColor greenColor]setStroke];
//Define line width and cap
CGContextSetLineWidth(ctx, TB_BACKGROUND_WIDTH);
CGContextSetLineCap(ctx, kCGLineCapButt);
CGContextDrawPath(ctx, kCGPathStroke);
UIGraphicsBeginImageContext(CGSizeMake(TB_SLIDER_SIZE,TB_SLIDER_SIZE));
CGContextRef imageCtx = UIGraphicsGetCurrentContext();
CGContextAddArc(imageCtx, self.frame.size.width/2 , self.frame.size.height/2, radius, 0, ToRad(self.self.startAngle), 0);
[[UIColor redColor]set];
CGContextSetLineWidth(imageCtx, TB_LINE_WIDTH);
CGContextDrawPath(imageCtx, kCGPathStroke);
//save the context content into the image mask
CGImageRef mask = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());
UIGraphicsEndImageContext();
CGContextSaveGState(ctx);
CGContextClipToMask(ctx, self.bounds, mask);
CGImageRelease(mask);
//list of components
CGFloat components[8] = {
0.0, 0.0, 1.0, 1.0, // Start color - Blue
1.0, 1.0, 1.0, 1.0 }; // End color - Violet
CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, components, NULL, 2);
CGColorSpaceRelease(baseSpace), baseSpace = NULL;
//Gradient direction
CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
//Draw the gradient
CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient), gradient = NULL;
CGContextRestoreGState(ctx);
/** Draw the handle **/
[self drawTheHandle:ctx];
}
CGContextDrawPath(imageCtx, kCGPathFill);
make the backgroup width and line width to 140 and it works!!
#define TB_BACKGROUND_WIDTH 140 //The width of the dark background
#define TB_LINE_WIDTH 140 //The width of the active area (the gradient) and the width of the handle

Quartz UIImage with rounded corners and transparent background on iOS

I have used this solution to apply corner radius to UIImage in Quartz. It works fine like I predicted.
However the corners area outside of the image are not transparent but somewhat colored in white:
The image above shows top left corner of processed image that is opaque and not transparent.
I want cropped-out edges to be totally transparent. How can I achieve this?
EDIT: If I want to do this with UIImageView I would already done this. So please keep in mind that I want to do this with Quartz on UIImage object not UIImageView.
SOLUTION: The problem is actually not in the drawing code but rather in writing that image to the file system. I've saved image as JPEG an not as PNG. That's why corners were not transparent cos JPEG does not have alpha filter.
I usually use a custom category implemented on UIImage to crop the images with round corners. This was taken from this answer.
void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight, BOOL top, BOOL bottom)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM (context, ovalWidth, ovalHeight);
fw = CGRectGetWidth (rect) / ovalWidth;
fh = CGRectGetHeight (rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2);
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 0);
NSLog(#"bottom? %d", bottom);
if (top) {
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 3);
} else {
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 0);
}
if (bottom) {
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 3);
} else {
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 0);
}
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 0);
CGContextClosePath(context);
CGContextRestoreGState(context);
}
- (UIImage *)roundCornersOfImage:(UIImage *)source roundTop:(BOOL)top roundBottom:(BOOL)bottom {
int w = source.size.width;
int h = source.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextBeginPath(context);
CGRect rect = CGRectMake(0, 0, w, h);
addRoundedRectToPath(context, rect, 4, 4, top, bottom);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), source.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
}
add these bellow lines in your drawRect method ..
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
///your another code here
}
after create Context it required to clear another context from that Rect... so after that line add this line CGContextClearRect(context, rect);.
For transparent use this:
const float colorMasking[6] = {1.0, 1.0, 0.0, 0.0, 1.0, 1.0};
yourImage = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(yourImage.CGImage, colorMasking)];
EDIT : Add this both line in method of UIImage category
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
The problem is actually not in the drawing code but rather in writing that image to the file system. I've saved image as JPEG an not as PNG. That's why corners were not transparent cos JPEG does not have alpha filter.
Just replaced this line of code:
[UIImageJPEGRepresentation(image, 0.75) writeToFile:path atomically:YES];
... with this one:
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
Try this code
Image.layer.cornerRadius = 10.0;
Image.layer.borderColor = [UIColor blackColor].CGColor;
Image.layer.borderWidth = 0.5;
Image.clipsToBounds = YES;
Image.backgroundColor = [UIColor clearColor];
Hope it helps you
EDIT :-
I think you just need to add this :-
Image.clipsToBounds = YES;

UIView: Draw at double the size

I have a UIView with a dynamically generated graphic context. Its normal size is 100x100, but it can be scaled up to 200x200, so I want its size to be actually 200x200 in order to appear nicely and not blurred however it is displayed.
How can always draw it 200x200 in drawRect, being it displayed at a size of 100 or at a size of 200? If I'm showing it at 100x100, the rect passed to drawRect is smaller than the area I need to draw into.
My code:
- (void) drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
// prevent the drawings to be flipped
CGContextTranslateCTM(ctx, 0, rect.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextDrawImage(ctx, CGRectMake(0, 0, rect.size.width, rect.size.height), [UIImage imageNamed:#"actionBg.png"].CGImage);
// generate the overlay
if ([self isActive] == NO && self.fullDelay != 0) { // TODO: remove fullDelay check!
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
CGContextRef overlayCtx = UIGraphicsGetCurrentContext();
int segmentSize = (rect.size.height / [self fullDelay]);
for (int i=0; i<[self fullDelay]; i++) {
float alpha = 0.9 - (([self fullDelay] * 0.1) - (i * 0.1));
[[UIColor colorWithRed:120.0/255.0 green:14.0/255.0 blue:14.0/255.0 alpha:alpha] setFill];
if (currentDelay > i) {
CGRect r = CGRectMake(0, i * segmentSize, rect.size.width, segmentSize);
CGContextFillRect(overlayCtx, r);
}
[[UIColor colorWithRed:1 green:1 blue:1 alpha:0.3] setFill];
CGRect line = CGRectMake(0, (i * segmentSize) + segmentSize - 1 , rect.size.width, 1);
CGContextFillRect(overlayCtx, line);
}
UIImage *overlay = UIGraphicsGetImageFromCurrentImageContext();
UIImage *overlayMasked = [TDUtilities maskImage:overlay withMask:[UIImage imageNamed:#"actionMask.png"]];
// prevent the drawings to be flipped
CGContextTranslateCTM(ctx, 0, rect.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
// put the overlay
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextDrawImage(ctx, rect, overlayMasked.CGImage);
CGContextSetBlendMode(ctx, kCGBlendModeNormal);
UIGraphicsEndImageContext();
}
// prevent the drawings to be flipped
CGContextTranslateCTM(ctx, 0, rect.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
// draw the delay symbol
CGContextDrawImage(ctx, rect, [UIImage imageNamed:#"delaySymbol.png"].CGImage);
CGContextSetAlpha(ctx, 0.8);
// draw the symbol
NSString *imgName = [K_ACTION_IMAGES objectAtIndex:[self actionType]];
CGContextDrawImage(ctx, rect, [UIImage imageNamed:imgName].CGImage);
CGContextSetAlpha(ctx, 1);
// draw the delay number
imgName = [NSString stringWithFormat:#"%d.png", [self fullDelay]];
CGContextDrawImage(ctx, rect, [UIImage imageNamed:imgName].CGImage);
// draw the priority number
imgName = [NSString stringWithFormat:#"%d.png", [self actionType]];
CGContextDrawImage(ctx, CGRectMake(32, 0, rect.size.width, rect.size.height), [UIImage imageNamed:imgName].CGImage);
}
Have you called setNeedsDisplay method for you view after setting its frame

Can draw on only half of UIView

I am trying to draw grid on a UIView on a UIScrollView.
The width of UIView is about 1000 pixels. However, I can draw lines only
about first 340 pixels of the UIView. Can anyone help me on this?
The drawGrid function is
- (void)drawRect:(CGRect)rect
{
NSInteger width = 25 * 5 * 10;
NSInteger height = (10 * 2 + 10) * 12;
NSInteger i;
//Get the CGContext from this view
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw rectangle with a blue stroke color and white fill color
CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
CGContextSetLineWidth(context, 2.0);
CGContextAddRect(context, CGRectMake(0.0, 0.0, width, height));
CGContextFillPath(context);
// Draw grid with red color
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
// Set the width of the pen mark
CGContextSetLineWidth(context, 0.2);
for (i = 0; i < height; i += 5)
{
if (i % 25 == 0)
{
CGContextSetLineWidth(context, 0.4);
// Draw a line
CGContextMoveToPoint(context, i, 0.0);
CGContextAddLineToPoint(context, i, width);
CGContextStrokePath(context);
CGContextSetLineWidth(context, 0.2);
}
else
{
// Draw a line
CGContextMoveToPoint(context, i, 0.0);
CGContextAddLineToPoint(context, i, width);
CGContextStrokePath(context);
}
}
for (i = 0; i < width; i += 5)
{
if (i % 25 == 0)
{
CGContextSetLineWidth(context, 0.4);
// Draw a line
CGContextMoveToPoint(context, 0.0, i);
CGContextAddLineToPoint(context, height, i);
CGContextStrokePath(context);
CGContextSetLineWidth(context, 0.2);
}
else
{
// Draw a line
CGContextMoveToPoint(context, 0.0, i);
CGContextAddLineToPoint(context, height, i);
CGContextStrokePath(context);
}
}
}
I am also setting up the UIScrollView and UIView as follows:
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
waveScrollView = [[WaveScrollView alloc] initWithFrame:frame];
CGRect waveframe = CGRectMake(0, 0, 25 * 5 * 10, (10 * 2 + 10) * 12);
EKGWaveView *ekgWaveView = [[EKGWaveView alloc] initWithFrame:waveframe];
waveScrollView.contentSize = CGSizeMake(waveframe.size.width, waveframe.size.height);
waveScrollView.maximumZoomScale = 4.0;
waveScrollView.minimumZoomScale = 0.75;
waveScrollView.clipsToBounds = YES;
waveScrollView.aView = ekgWaveView;
[waveScrollView addSubview:ekgWaveView];
waveScrollView.delegate = self;
[self.view addSubview:waveScrollView];
}
I appreciate any help. Thanks.
I'm pretty sure you've got some of your variables mixed up.
You're looping i from 0 to height but then you're using i as your x parameter when creating lines, and using width as your y parameter.

Rounded rect with Gradient color

I have not really done much programming with Core Graphics. And I tend to stick with QuartzCore now that it does a lot of what I need through the layer property :)
However, I have a UIView, which is currently gradient. I'd like to add rounded corners to this UIView and the layer property does not do this when I draw the gradient:
- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 0.95, // Start color
1.0, 1.0, 1.0, 0.60 }; // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGRect currentBounds = self.bounds;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
}
I am not really sure where I should be rounding in the drawRect method. Thanks.
Have you checked previous question postings? I read one a while back about masking UIViews. I think the same applies pretty much on all objects which use drawRect
How to mask a square image into an image with round corners in the iPhone SDK?
Here's what I did, and it works fine as far as I can tell.
First, I borrowed Mr NilObject's code snippet from the above mentioned post.
I modified it to fit in an object (as he wrote it as a C function instead of a method)
I subclass UIView to create my own custom view. I overload initWithRect: to make my background transparent.
So basically:
set transparent background (in init), or clipping will be uggly
in drawRect, first clip, then draw inside the clipped area
The following is a working example:
//
// TeleView.m
//
#import "TeleView.h"
#implementation TeleView
/**** in init methods, set background to transparent,
otherwise, clipping shows a black background ****/
- (id) initWithFrame:(CGRect)frame {
if((self = [super initWithFrame:frame])) {
[self setBackgroundColor:[UIColor colorWithWhite:0.0f alpha:0.0f]];
}
return self;
}
- (void) clipCornersToOvalWidth:(float)ovalWidth height:(float)ovalHeight
{
float fw, fh;
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height);
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM (context, ovalWidth, ovalHeight);
fw = CGRectGetWidth (rect) / ovalWidth;
fh = CGRectGetHeight (rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2);
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
CGContextClosePath(context);
CGContextRestoreGState(context);
}
-(void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
/**** here is what I modified. ****/
[self clipCornersToOvalWidth:20.0f height:20.0f];
CGContextClip(currentContext);
/**** below this is your own code ****/
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 0.0, 0.0, 0.60, // Start color
0.0, 1.0, 0.0, 0.40 }; // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGRect currentBounds = self.bounds;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
}
#end
NSArray *colors = [NSArray arrayWithObjects:fromColor.CGColor,toColor.CGColor, nil];
NSNumber *stopOne = [NSNumber numberWithFloat:0.0];
NSNumber *stopTwo = [NSNumber numberWithFloat:1.0];
NSArray *locations = [NSArray arrayWithObjects:stopOne, stopTwo, nil];
CAGradientLayer *headerLayer = [CAGradientLayer layer];
headerLayer.colors = colors;
headerLayer.locations = locations;
headerLayer.borderColor = borderColor.CGColor; // border line color**strong text**
headerLayer.borderWidth = width;// For Thickness of border line
headerLayer.cornerRadius = radius;//For Rounded Corner if You want to make rounded Corner
headerLayer.frame = frame;
[view.layer insertSublayer:headerLayer atIndex:0];
Also make sure to import "QuartzCore" framework