CGContextDrawLinearGradient confusion. Need clarification - objective-c

I am have been experimenting with CGContextDrawLinearGradient and I terribly confused with what start point and end point mean? I thought they mean coordinates on the current CGContext so if I define start point to be 0,0 and end point to be 100,100, i would get a square with gradient. I get something else altogether that I just cannot connect to my co-ordinates.
This is the code that I have:
- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef current_context = UIGraphicsGetCurrentContext();
CGContextSaveGState(current_context);
// Gradient
CGFloat locations[3] = {0.0, 0.5, 1.0};
CGFloat components[12] = {1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0};
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, 3);
CGPoint startPoint = CGPointMake(0, 0);
CGPoint endPoint = CGPointMake(40, 40);
CGContextDrawLinearGradient(current_context, gradient, startPoint, endPoint, 0);
// Shadow
CGContextSetShadow(current_context, CGSizeMake(4,7), 1.0);
// Image
UIImage *logoImage = [UIImage imageNamed:#"logo.png"];
[logoImage drawInRect:bounds];
CGContextRestoreGState(current_context);
}
Thanks for your help in advance..

Most of your code is quite OK; the problem occurs in the following lines:
CGPoint startPoint = CGPointMake(0, 0);
CGPoint endPoint = CGPointMake(40, 40);
CGContextDrawLinearGradient(current_context, gradient, startPoint, endPoint, 0);
CGContextDrawLinearGradient expects to get a start and an end point (defining a line, not two diagonal edges of a square!).
The gradient is then drawn by colored lines perpendicular to this controlling line. The drawing starts with a line going through startPoint (perpendicular to the line between startPoint and endPoint) using the start color (color at location 0). The next line is drawn through a point 'one pixel' closer to the endPoint, with a color calculated to be somewhere between the start and the end or next color (depending of the number of color locations). Finally a line is drawn through the endPoint (again perpendicular...) using the end color.
The advantage of using a (controlling) line instead of a square is, that the gradient can be drawn in any direction; horizontally, vertically, somewhere between, only depending of the direction of the given line.
In your example code, the gradient should be diagonally, as your line has an angle of 45° to the x-axis :-).

code from raywanderlich tutorial
override func drawRect(rect: CGRect) {
//2 - get the current context
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.CGColor, endColor.CGColor]
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations:[CGFloat] = [0.0, 1.0]
//5 - create the gradient
let gradient = CGGradientCreateWithColors(colorSpace,
colors,
colorLocations)
//6 - draw the gradient
var startPoint = CGPoint.zeroPoint
var endPoint = CGPoint(x:0, y:self.bounds.height)
CGContextDrawLinearGradient(context,
gradient,
startPoint,
endPoint,
0)
}

Related

Determine UIFont size with CGSize Points or Pixels

I can make a CGRect with an exact defined PointSize e.g (20x20) and on this way i can exactly calculate the real size (cm or inch) on the Screen.
-(void) drawRect:(CGRect)rect{
[super drawRect:rect];
CGRect rectangle = CGRectMake(0, 0, 20, 20);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextFillRect(context, rectangle);
}
I would like to determine the size of the UIFont (always only one Charackter "A..Z" or "1..9") somehow in a simular way, so that i can calculate at least the real height on the Screen.
Is it possible to calculate the Font size from CGSize to UIfont Size, so that it really matches on the screen ?
I have found a Solution for this kind of Problem.
If you want to have an UIFont to fit a CGRect or a Label, it won't fit the CGRect in the most cases. The Reason are the Font specific paddings.
If you want a Font to fit a CGRect, you must know wheter to use a lower or Upper Case Letters, an then to set font.xHeigth or the font.capHeight as font.pointSize. Therefore you'll get a bigger font.pointsize.
This little CodeSnippet solved my Problem:
+(CGFloat) fitFontSize:(UIFont*) font{
CGFloat fontSize = font.pointSize;
bool fontSizeAdjusted = false;
while (!fontSizeAdjusted) {
CGFloat xHeight = font.xHeight;
if( fontSize-xHeight > 0.1 ){
font = [font fontWithSize:font.pointSize+1];
}else{
fontSizeAdjusted = true;
fontSize = font.pointSize;
}
}
return fontSize;
}
This Article helped me to learn more about UIFonts

What is wrong with this way of using CGAffineTransform?

I want to make a graph in a UIView that shows numerical data. So I need to draw axis, a few coordinate lines, some tick marks, and then the data as connected straight lines. The data might typically consist of a few hundred x values in the range -500. to +1000. with corresponding y values in the range 300. to 350.
So I thought a good approach would be to transform the coordinates of the UIView so (for the example values given) the left side of the view is -500, and right side is 1000, the top is 400 and the bottom is 300. And y increases upwards. Then in drawRect: I could write a bunch of CGContextMoveToPoint() and CGContextAddLineToPoint() statements with my own coordinate system and not have to mentally translate each call to the UIView coordinates.
I wrote the following function to generate my own CGContextRef but it doesn't do what I expected. I've been trying variations on it for a couple days now and wasting so much time. Can someone say how to fix it? I realize I can't get clear in my mind whether the transform is supposed to specify the UIView coordinates in terms of my coordinates, or vice versa, or something else entirely.
static inline CGContextRef myCTX(CGRect rect, CGFloat xLeft, CGFloat xRight, CGFloat yBottom, CGFloat yTop) {
CGAffineTransform ctxTranslate = CGAffineTransformMakeTranslation(xLeft, rect.size.height - yTop);
CGAffineTransform ctxScale = CGAffineTransformMakeScale( rect.size.width / (xRight - xLeft), -rect.size.height / (yTop - yBottom) ); //minus so y increases toward top
CGAffineTransform combinedTransform = CGAffineTransformConcat(ctxTranslate, ctxScale);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextConcatCTM(c, combinedTransform);
return c;
}
The way I'm using this is that inside drawRect I just have:
CGContextRef ctx = myCTX(rect, self.xLeft, self.xRight, self.yBottom, self.yTop);
and then a series of statements like:
CGContextAddLineToPoint(ctx, [x[i] floatValue], [y[i] floatValue]);
I figured this out by experimenting. The transform requires 3 steps instead of 2 (or, if not required, at least it works this way):
static inline CGContextRef myCTX(CGRect rect, CGFloat xLeft, CGFloat xRight, CGFloat yBottom, CGFloat yTop) {
CGAffineTransform translate1 = CGAffineTransformMakeTranslation(-xLeft, -yBottom);
CGAffineTransform scale = CGAffineTransformMakeScale( rect.size.width / (xRight - xLeft), -rect.size.height / (yTop - yBottom) );
CGAffineTransform transform = CGAffineTransformConcat(translate1, scale);
CGAffineTransform translate2 = CGAffineTransformMakeTranslation(1, rect.size.height);
transform = CGAffineTransformConcat(transform, translate2);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextConcatCTM(c, transform);
return c;
}
You use this function inside drawRect. In my case the xLeft, xRight, etc. values are properties of a UIView subclass and are set by the viewController. So the view's drawRect looks like so:
- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSaveGState(c);
CGContextRef ctx = myCTX(rect, self.xLeft, self.xRight, self.yBottom, self.yTop);
…
all of the CGContextMoveToPoint(), CGContextAddLineToPoint(), calls to
draw your desired lines, rectangles, curves, etc. but not stroke or fill them
…
CGContextRestoreGState(c);
CGContextSetLineWidth(c, 1);
CGContextStrokePath(c);
}
The CGContextSetLineWidth call isn't needed if you want a line width of 1. If you don't restore the graphics state before strokePath the path width is affected by the scaling.
Now I have to figure out how to draw text onto the view.

CALayer: Linear Gradient Issue

I am drawing a Linear Gradient on one of my CALayers with some colors, but randomly, with the same input, the colors are drawn on the screen as a pink color.
The code is as follows:
bottomComponents = bottomColor.colorComponents;
topComponents = topColor.colorComponents;
middleComponents = middleColor.colorComponents;
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
size_t numberOfLocations = 3;
CGFloat locations[3] = {0.0f, MIDDLE_POINT, 1.0f};
CGFloat components[12] =
{
topComponents.red, topComponents.green, topComponents.blue, topComponents.alpha,
middleComponents.red, middleComponents.green, middleComponents.blue, middleComponents.alpha,
bottomComponents.red, bottomComponents.green, bottomComponents.blue, bottomComponents.alpha
};
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, numberOfLocations);
CGRect currentBounds = self.bounds;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint bottomCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetHeight(currentBounds));
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, bottomCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
Where colorComponents is just returning a struct with the color components.
When I output the color in a log, it is the proper color, but when it shows up on screen, regardless of the start colors, it is a pink-ish color.
Is there anything that I have done wrong that could cause the random pink to show up?
The pink shows up completely sporadically. I will load from the exact same values and rarely, but surely, it will show up pink. Loading from different values yields the same results. Its happening around 1-2% of the time.
Any chance some of the times you use UIColor predefined colors? (For example greenColor)
I found those don't generate proper components.
Liviu

CGContextAddEllipse - overlapping get's clipped - Quartz

I like to draw a glass with a few Elements
- Top Ellipse
- Bottom Ellipse
- and the Lines Inbetween
Next, it should be filled with a Gradient. The Elements work, but at the point, where the middle of the glass comes in touch with the top or bottom ellipse the area get's clipped.
- (void)drawRect:(CGRect)rect
{
CGPoint c = self.center;
// Drawing code
CGContextRef cx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(cx, 1.0);
[[UIColor whiteColor] setStroke];
// DrawTheShapeOfTheGlass
CGContextBeginPath(cx);
// Top and Bottom Ellipse
CGContextAddEllipseInRect(cx, CGRectMake(0, 0, 100, 20));
CGContextAddEllipseInRect(cx, CGRectMake(10, 90, 80, 20));
// Define the points for the Area inbetween
CGPoint points[] = { {0.0,10.0},{10.0,100.0},{90.0,100.0},{100.0,10.0} };
CGContextAddLines(cx, points, 4);
CGContextClosePath(cx);
// Clip, that's only the Clipped-Area wil be filled with the Gradient
CGContextClip(cx);
// CreateAndDraw the Gradient
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat colorSpace[] = {1.0f, 1.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f, 1.0f };
CGFloat locations[] = { 0.0, 1.0 };
CGGradientRef myGradient = CGGradientCreateWithColorComponents(rgbColorSpace, colorSpace, locations, 2);
CGPoint s = CGPointMake(0, 0);
CGPoint e = CGPointMake(100, 100);
CGContextDrawLinearGradient(cx, myGradient, s, e, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
CGColorSpaceRelease(rgbColorSpace);
CGGradientRelease(myGradient);
}
Here how it looks like:
Is there any possibility to "fill" the whole ellipse? I played around with BlendModes but it didn't help.
Thanks
Try replacing the points[] initialization code with the following...
CGPoint points[] = {{0.0,10.0},{100.0,10.0},{90.0,100.0},{10.0,100.0}};
CoreGraphics uses the non-zero winding count rule to determine how to fill a path. Since ellipses are drawn clockwise and your trapezoid was drawn counter clockwise, the overlapping regions were not filled. Changing the drawing order of the trapezoid to clockwise will result in an object that is completely filled.

Linear gradient aliasing with CoreGraphics

I'm trying to emulate the color tint effect from the UITabBarItem.
When I draw a linear gradient at an angle, I get visible aliasing in the middle part of the gradient where the two colors meet at the same location. Left is UITabBarItem, right is my gradient with visible aliasing (stepping):
Here is the snippet of relevant code:
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSaveGState(c);
CGContextScaleCTM(c, 1.0, -1.0);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[16] = {1,1,1,1,
109.0/255.0,175.0/255.0,246.0/255.0,1,
31.0/255.0,133.0/255.0,242.0/255.0,1,
143.0/255.0,194.0/255.0,248.0/255.0,1};
CGFloat locations[4] = {0.0, 0.62, 0.62, 1};
CGGradientRef colorGradient =
CGGradientCreateWithColorComponents(colorSpace, components,
locations, (size_t)4);
CGContextDrawLinearGradient(c, colorGradient, CGPointZero,
CGPointMake(size.width*1.0/3.9, -size.height),0);
CGGradientRelease(colorGradient);
CGColorSpaceRelease(colorSpace);
CGContextRestoreGState(c);
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
What do I need to change, to get a smooth angled gradient like in UITabBarItem?
What is the interpolation quality of your context set to? CGContextGetInterpolationQuality()/CGContextSetInterpolationQuality(). Try changing that if it's too low.
If that doesn't work, I'm curious what happens if you draw the gradient vertically (0,Ymin)-(0,Ymax) but apply a rotation transformation to your context...
As a current workaround, I draw the gradient at double resolution into an image and then draw the image with original dimensions. The image scaling that occurs, takes care of the aliasing. At the pixel level the result is not as smooth as in the UITabBarItem, but that probably uses an image created in Photoshop or something similar.