UIView with custom shape - ios

I want to have a UIElement (any of UIView, UIButton, UILabel etc.) with custom shape lets say a triangle.
How do you suggest to achieve it.
Thanks in advance.

Here is a sample of a UIView subclass (triangle):
#implementation TriangleView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctx);
CGContextMoveToPoint (ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect)); // top left
CGContextAddLineToPoint(ctx, CGRectGetMidX(rect), CGRectGetMinY(rect)); // mid right
CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect)); // bottom left
CGContextClosePath(ctx);
CGContextSetRGBFillColor(ctx, 241/255.0, 241/255.0, 241/255.0, 1);
CGContextFillPath(ctx);
}
#end

Related

How to convert tableview cell to rounded corner with shadow in iOS 9.0 or later

I want to show tableview cell like above image.
Please help me out.
If you use normal table view cell
cell.contentView.layer.cornerRadius = 7.0f;
cell.contentView.layer.masksToBounds = YES;
If you use custom table view cell
cell.layer.cornerRadius = 7.0f;
cell.layer.masksToBounds = YES;
clear background color of UITableView in storyboard. Then you will be able to see the change.
For Cell Row Height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 44; //It default size.If you want to change to other size you can change.
}
To show rounded corner cell you can set corner radius.
For the current design you can create a custom UItableViewCell and set corner radius to it.
yourCustomCell.layer.cornerradius = 6.0f
In that UItableViewCell you need to add other labels as per your requirement.
Try this step you display image like:
you are add one view and top = 8, bottom = 8, left = 16, right = 16 set constraint in cell content view.
view.layer.cornerradius = 5.0f;
table background color set clear.
If you want rounded corners and shadow in an UITableviewCell you need to implement a (custom) UIView in the cell.
One way doing that is:
#interface customCell ()
#property (strong, nonatomic) IBOutlet UIView *someView;
#end
#implementation customCell
- (void)awakeFromNib {
[super awakeFromNib];
//Set the corner radius
self.someView.layer.cornerRadius = 5.0f;
// Add shadow
[self applyShadow];
}
- (void)applyShadow {
// Add shadow
[self.layer setShadowColor:[[UIColor blackColor] CGColor]];
[self.layer setShadowOffset:CGSizeMake(0, 2)];
[self.layer setShadowRadius:2.0];
[self.layer setShadowOpacity:0.5];
self.clipsToBounds = false;
self.layer.masksToBounds = false;
}
Add the custom View to the table View cell and set the below class:
CustomView.h
#import <UIKit/UIKit.h>
#import "Common.h"
#interface CustomView : UIView
{
IBInspectable UIColor *startColor;
IBInspectable UIColor *endColor;
}
#end
CustomView.m
#import "CustomView.h"
IB_DESIGNABLE
#implementation CustomView
- (void)drawRect:(CGRect)rect
{
CGContextRef context=UIGraphicsGetCurrentContext();
UIColor *ShadowColor=[UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
UIColor *backGround=[UIColor whiteColor];
CGFloat outerMagian=2.0;
CGRect outerRect=CGRectInset(self.bounds, outerMagian, outerMagian);
CGPathRef outerPath=createRoundedRectForRect(outerRect, 0.0);
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, CGSizeMake(2, 2), 3.0, ShadowColor.CGColor);
CGContextSetFillColorWithColor(context, backGround.CGColor);
CGContextAddPath(context, outerPath);
CGContextFillPath(context);
CGContextRestoreGState(context);
CGFloat borderMarian=1.0;
CGRect borderRect=CGRectInset(self.bounds, borderMarian, borderMarian);
CGPathRef borderPath=createRoundedRectForRect(borderRect, 0.0);
CGContextSaveGState(context);
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0].CGColor);
CGContextAddPath(context, borderPath);
CGContextStrokePath(context);
CGContextRestoreGState(context);
CGPathRelease(outerPath);
CGPathRelease(borderPath);
UIBezierPath *path=[UIBezierPath bezierPathWithRoundedRect:outerRect cornerRadius:0.0];
[path addClip];
drawLinearGradient(context,outerRect, startColor.CGColor, endColor.CGColor);
}
#end
Common.h
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#interface Common : NSObject
CGMutablePathRef createRoundedRectForRect(CGRect rect, CGFloat radius);
void drawLinearGradient(CGContextRef context, CGRect rect, CGColorRef startColor, CGColorRef endColor);
#end
Common.m
#import "Common.h"
#implementation Common
CGMutablePathRef createRoundedRectForRect(CGRect rect, CGFloat radius)
{
CGMutablePathRef path=CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect), CGRectGetMaxX(rect), CGRectGetMaxY(rect), radius);
CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect), CGRectGetMinX(rect), CGRectGetMaxY(rect), radius);
CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect), CGRectGetMinX(rect), CGRectGetMinY(rect), radius);
CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect), CGRectGetMaxX(rect), CGRectGetMinY(rect), radius);
CGPathCloseSubpath(path);
return path;
}
void drawLinearGradient(CGContextRef context, CGRect rect, CGColorRef startColor, CGColorRef endColor)
{
CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
CGFloat locations[]={0.0,1.0};
NSArray *color=#[(__bridge id)startColor,(__bridge id)endColor];
CGGradientRef gradient=CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)color, locations);
CGPoint startPoint=CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint=CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGContextSaveGState(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
#end

Draw Triangles inside Circle Objective-C [duplicate]

For an iPhone application I want to draw a circle, that is only for an x percentage filled.
Something like this:
I have no problems calculating the radius, the degrees or the radians, that is no problem. Also drawing the circle is already done. But how do I get the iPhone SDK to draw the part that is filled.
I can draw a rectangle that size, but not part of a circle.
I just want to draw that on a a normal context.
Hope someone can give me any pointers here.
A lot of people have showed you how this can be done in Core Graphics but it can also be done with Core Animation which gives the big addition of easily being able to animate the percentage of the pie shape.
The following code will create both the ring and the partly filled layers (even though you said that you already can draw the ring) since its nice to have both the ring and the pie shape to be drawn using the same method.
If you animate the strokeStart or strokeEnd properties of the pieShape layer you will have the percentage animate. As with all Core Animation code you will need to add QuartzCore.framework to your project and include <QuartzCore/QuartzCore.h> in your code.
// Create a white ring that fills the entire frame and is 2 points wide.
// Its frame is inset 1 point to fit for the 2 point stroke width
CGFloat radius = MIN(self.frame.size.width,self.frame.size.height)/2;
CGFloat inset = 1;
CAShapeLayer *ring = [CAShapeLayer layer];
ring.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, inset, inset)
cornerRadius:radius-inset].CGPath;
ring.fillColor = [UIColor clearColor].CGColor;
ring.strokeColor = [UIColor whiteColor].CGColor;
ring.lineWidth = 2;
// Create a white pie-chart-like shape inside the white ring (above).
// The outside of the shape should be inside the ring, therefore the
// frame needs to be inset radius/2 (for its outside to be on
// the outside of the ring) + 2 (to be 2 points in).
CAShapeLayer *pieShape = [CAShapeLayer layer];
inset = radius/2 + 2; // The inset is updated here
pieShape.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, inset, inset)
cornerRadius:radius-inset].CGPath;
pieShape.fillColor = [UIColor clearColor].CGColor;
pieShape.strokeColor = [UIColor whiteColor].CGColor;
pieShape.lineWidth = (radius-inset)*2;
// Add sublayers
// NOTE: the following code is used in a UIView subclass (thus self is a view)
// If you instead chose to use this code in a view controller you should instead
// use self.view.layer to access the view of your view controller.
[self.layer addSublayer:ring];
[self.layer addSublayer:pieShape];
Use CGContext's arc functions:
CGContextAddArc(context,
centerX,
centerY,
radius,
startAngleRadians,
endAngleRadians,
clockwise ? 1 : 0);
See the documentation for CGContextAddArc().
Try this:
CGContextMoveToPoint(the center point)
CGContextAddLineToPoint(the starting point of the fill path on the circumference)
CGContextAddArcToPoint(the ending point of the fill path on the circumference)
CGContextAddLineToPoint(the center point)
CGContextFillPath
I implemented a pie progress view that looks similar to what you are doing. It's open source. Hopefully the source code will help.
SSPieProgressView.h source
SSPieProgressView.m source
CircleViewController.h
#import <UIKit/UIKit.h>
#interface CircleViewController : UIViewController
#end
CircleViewController.m
#import "CircleViewController.h"
#import "GraphView.h"
#interface CircleViewController ()
#end
#implementation CircleViewController
- (void)viewDidLoad {
[super viewDidLoad];
GraphView *graphView = [[GraphView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
graphView.backgroundColor = [UIColor whiteColor];
graphView.layer.borderColor = [UIColor redColor].CGColor;
graphView.layer.borderWidth = 1.0f;
[self.view addSubview:graphView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
GraphView.h
#import <UIKit/UIKit.h>
#interface GraphView : UIView
#end
GraphView.m
#import "GraphView.h"
#implementation GraphView
- (void)drawRect:(CGRect)rect {
CGPoint circleCenter = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
[self drawCircleWithCircleCenter:(CGPoint) circleCenter radius:80 firstColor:[UIColor blueColor].CGColor secondeColor:[UIColor redColor].CGColor lineWidth:2 startDegree:0 currentDegree:90];
//[self drawCircleWithCircleCenter2:(CGPoint) circleCenter radius:80 firstColor:[UIColor blueColor].CGColor secondeColor:[UIColor redColor].CGColor lineWidth:2 startDegree:0 currentDegree:90];
}
- (void)drawCircleWithCircleCenter:(CGPoint) circleCenter
radius:(CGFloat)radius
firstColor:(CGColorRef)firstColor
secondeColor:(CGColorRef)secondeColor
lineWidth:(CGFloat)lineWidth
startDegree:(float)startDegree
currentDegree:(float)endDegree {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, lineWidth);
CGContextMoveToPoint(context, circleCenter.x, circleCenter.y);
CGContextAddArc(context, circleCenter.x , circleCenter.y, radius, [self radians:startDegree], [self radians:endDegree], 0);
CGContextSetFillColorWithColor(context, firstColor);
CGContextFillPath(context);
CGContextMoveToPoint(context, circleCenter.x, circleCenter.y);
CGContextAddArc(context, circleCenter.x, circleCenter.y, radius, [self radians:endDegree], [self radians:startDegree], 0);
CGContextSetFillColorWithColor(context, secondeColor);
CGContextFillPath(context);
}
- (void)drawCircleWithCircleCenter2:(CGPoint) circleCenter
radius:(CGFloat)radius
firstColor:(CGColorRef)firstColor
secondeColor:(CGColorRef)secondeColor
lineWidth:(CGFloat)lineWidth
startDegree:(float)startDegree
currentDegree:(float)endDegree {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, lineWidth);
CGContextMoveToPoint(context, circleCenter.x, circleCenter.y);
CGContextAddArc(context, circleCenter.x , circleCenter.y, radius, [self radians:startDegree], [self radians:endDegree], 0);
CGContextSetFillColorWithColor(context, firstColor);
CGContextFillPath(context);
CGContextMoveToPoint(context, circleCenter.x, circleCenter.y);
CGContextAddArc(context, circleCenter.x, circleCenter.y, radius, [self radians:endDegree], [self radians:startDegree], 0);
CGContextSetStrokeColorWithColor(context, secondeColor);
CGContextStrokePath(context);
}
-(float) radians:(double) degrees {
return degrees * M_PI / 180;
}
#end
note: you can use one of the 2 methods:
"drawCircleWithCircleCenter" or "drawCircleWithCircleCenter2"
this code if you want to split cell on 2 parts only
if you want to split cell on more than 2 parts you can check this : "Drawing a circle ,filled different parts with different color" and check the answer start with this Phrase "we have 6 class"
Well, since nobody used NSBezierPath so far, I figured I could provide the solution I recently used for the same problem:
-(void)drawRect:(NSRect)dirtyRect
{
double start = -10.0; //degrees
double end = 190.0; //degrees
NSPoint center = NSMakePoint(350, 200);
double radius = 50;
NSBezierPath *sector = [NSBezierPath bezierPath];
[sector moveToPoint:center];
[sector appendBezierPathWithArcWithCenter:center radius:radius startAngle:start endAngle:end];
[sector lineToPoint:center];
[sector fill];
}
Below is a full method I am using that does this with Core Graphics, adapting and expanding on mharper's comment above.
This code is for OSX Cocoa, but could easily be changed to iOS, by modifying how you get the context.
- (void)drawPieShapedCircleWithRadius:(CGFloat)radius
strokeColor:(CGColorRef)strokeColor
fillColor:(CGColorRef)fillColor
lineWidth:(CGFloat)lineWidth
currentDegrees:(float)currentDegrees
startDegrees:(float)startDegrees {
// get the context
CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
// Set the color of the circle stroke and fill
CGContextSetStrokeColorWithColor(context, strokeColor);
CGContextSetFillColorWithColor(context, fillColor);
// Set the line width of the circle
CGContextSetLineWidth(context, 1);
// Calculate the middle of the circle
CGPoint circleCenter = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
// Move the bezier to the center of the circle
CGContextMoveToPoint(context, circleCenter.x, circleCenter.y); // move to the center point
// Draw the arc from the start point (hardcoded as the bottom of the circle) to the center
CGContextAddLineToPoint(context, circleCenter.x, circleCenter.y + radius);
// Draw the arc around the circle from the start degrees point to the current degrees point
CGContextAddArc(context, circleCenter.x , circleCenter.y, radius, [self radians:startDegrees], [self radians:startDegrees + currentDegrees], 0);
// Draw the line back into the center of the circle
CGContextAddLineToPoint(context, circleCenter.x, circleCenter.y);
// Fill the circle
CGContextFillPath(context);
// Draw the line around the circle
CGContextStrokePath(context);
}
Try this code in a UIView, Example "MyChartClass"...
- (void)drawRect:(CGRect)rect {
int c=(int)[itemArray count];
CGFloat angleArray[c];
CGFloat offset;
int sum=0;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetAllowsAntialiasing(context, false);
CGContextSetShouldAntialias(context, false);
for(int i=0;i<[itemArray count];i++) {
sum+=[[itemArray objectAtIndex:i] intValue];
}
for(int i=0;i<[itemArray count];i++) {
angleArray[i]=(float)(([[itemArray objectAtIndex:i] intValue])/(float)sum)*(2*3.14);
CGContextMoveToPoint(context, radius, radius);
if(i==0)
CGContextAddArc(context, radius, radius, radius, 0,angleArray[i], 0);
else
CGContextAddArc(context, radius, radius, radius,offset,offset+angleArray[i], 0);
offset+=angleArray[i];
CGContextSetFillColorWithColor(context, ((UIColor *)[myColorArray objectAtIndex:i]).CGColor);
CGContextClosePath(context);
CGContextFillPath(context);
}
}
Implementation in your UIViewController
MyChartClass *myChartClass=[[MyChartClass alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
myChartClass.backgroundColor = [UIColor clearColor];
myChartClass.itemArray=[[NSArray alloc]initWithObjects:#"75",#"25", nil];
myChartClass.myColorArray=[[NSArray alloc]initWithObjects:[UIColor blackColor],[UIColor whiteColor], nil];
myChartClass.radius=100;
[self.view addSubview:myChartClass];
Regards.

drawRect method get called but the UIView cannot display

ModeButtonView is a subclass of UIView, and is already added as a subview of viewController.view:
#interface ModeButtonView ()
#property(nonatomic, strong) MonthModeButtonView *monthModeButton;
#end
-(instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (!self) {
return nil;
}
self.backgroundColor = [UIColor colorWithRed:0.192 green:0.663 blue:0.647 alpha:1];
self.monthModeButton = [[MonthModeButtonView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.5 * self.bounds.size.width, 0.5 * self.bounds.size.height)];
self.monthModeButton.center = self.center;
[self addSubview:self.monthModeButton];
return self;
}
The MonthModeButtonView is also a subclass of UIView, and it is added as a subview of ModeButtonView. Its drawRect method is as follows:
- (void)drawRect:(CGRect)rect {
NSLog(#"drawRect get called");
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, rect.origin.x, rect.origin.y);
CGPathAddLineToPoint(path, NULL, rect.size.width, rect.size.height);
CGPathMoveToPoint(path, NULL, rect.size.width, rect.origin.y);
CGPathAddLineToPoint(path, NULL, rect.origin.x, rect.size.height);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextAddPath(currentContext, path);
[[UIColor redColor] setStroke];
CGContextDrawPath(currentContext, kCGPathStroke);
CGPathRelease(path);
}
I run the program, the ModeButtonView is displayed well on the screen, and the drawRect method of MonthModeButtonView also get called, however, it cannot be displayed on the screen, while I have added it as a subview of ModeButtonView.
However, if I put the code of MonthModeButtonView's drawRect method into ModeButtonView's drawRect method directly, it get displayed. It seems the problem happens because MonthModeButtonView is a subview of MoodeButtonView, but why? Any idea about that?

coretext shows text from bottom to top of textfield

I'm drawing a textfield and i've added a textfield into the UIView. The text is within a path. It draws correctly, but the content starts at the bottom and ends at the top. Is there a way to fix this?
Here's my code:
// Draw text into a circle using Core Text and Quartz
- (void) drawRect:(CGRect)rect
{
[super drawRect: rect];
CGContextRef context = UIGraphicsGetCurrentContext();
self.layer.rasterizationScale = [[UIScreen mainScreen] scale];
// Flip the context
CGContextTranslateCTM(context, 0, 3);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0f, -1.0f));
// Stroke that path
CGContextAddPath(context, backPath);
CGContextSetLineWidth(context, 1.0f);
//[[UIColor blackColor] setStroke];
CGContextStrokePath(context);
// Fill that path
CGContextAddPath(context, backPath);
[[UIColor whiteColor] setFill];
CGContextFillPath(context);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);
CTFrameRef theFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, string.length),backPath, NULL);
CTFrameDraw(theFrame, context);
CFRelease(framesetter);
CFRelease(theFrame);
CFRelease(backPath);
}
This how I make the path:
- (id) initWithAttributedString: (NSAttributedString *) aString path: (vector<ofPoint>)paths
{
backPath = CGPathCreateMutable();
CGPathMoveToPoint(backPath, NULL, paths[0].x, paths[0].y); // Bottom left
for(int x=1; x< paths.size(); x++){
CGPathAddLineToPoint(backPath, NULL, paths[x].x,paths[x].y); // Bottom right
}
CGPathCloseSubpath(backPath);
if (!(self = [super initWithFrame:CGRectZero])) return self;
self.backgroundColor = [UIColor clearColor];
string = aString;
return self;
}
And to make the text field:
path.push_back(ofPoint(ofGetWidth()/4,ofGetHeight()/4));
// point to user
// path.push_back(ofPoint((position.x-(ofGetWidth()/4))/2,ofGetHeight()/4));
// point to right top
path.push_back(ofPoint(ofGetWidth()/4,ofGetHeight()/4));
// point to end x, pos y user
path.push_back(ofPoint((ofGetWidth()/4),(position.y-(ofGetHeight()/4))/2));
path.push_back(ofPoint((position.x-(ofGetWidth()/4))/2-100,(position.y-(ofGetHeight()/4))/2-100));
path.push_back(ofPoint((position.x-(ofGetWidth()/4))/2,(position.y-(ofGetHeight()/4))/2));
You are flipping the text matrix. Instead, flip the whole CTM:
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, self.bounds.size.height);

Draw a 5 pixel line on UIView [duplicate]

This question already has answers here:
What's the best approach to draw lines between views?
(2 answers)
Closed 9 years ago.
I have a very simple (well hopefully very simple) question. In Objective-C, how do you draw a line between two points and add it to a UIView? I have tried using a UIImageView and manipulating its Transform property, but that ends up turning the line into a square or a rectangle when using the following code:
[[self tline] setFrame:CGRectMake(start.x, start.y, width, 5)];
[[self tline] setTransform:CGAffineTransformMakeRotation(angle)];
I have two CGPoints, start and end, and I would like to draw a dynamic 5px line between the two points and add it to my subview.
BK:
The point start is the point where the user begins touching the screen, and the point end is the point where the user's finger is currently. Obviously this will move a lot during gameplay. I need to be able to move this line to connect these two points.
I am using the touchesBegan:, Moved:, and Ended: methods to create, move, and destroy the line.
CoreGraphics
I have the following code; how do I add this line to self.view?
CGContextRef c = UIGraphicsGetCurrentContext();
CGFloat color[4] = {1.0f, 1.0f, 1.0f, 0.6f};
CGContextSetStrokeColor(c, color);
CGContextBeginPath(c);
CGContextMoveToPoint(c, start.x, start.y);
CGContextAddLineToPoint(c, end.x, end.y);
CGContextSetLineWidth(c, 5);
CGContextSetLineCap(c, kCGLineCapRound);
CGContextStrokePath(c);
Custom UIView:
#import <UIKit/UIKit.h>
#interface DrawingView : UIView
#property (nonatomic) CGPoint start;
#property (nonatomic) CGPoint end;
- (void)drawRect:(CGRect)rect;
#end
#import "DrawingView.h"
#implementation DrawingView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetLineCap(context, kCGLineCapSquare);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor); //change color here
CGFloat lineWidth = 5.0; //change line width here
CGContextSetLineWidth(context, lineWidth);
CGPoint startPoint = [self start];
CGPoint endPoint = [self end];
CGContextMoveToPoint(context, startPoint.x + lineWidth/2, startPoint.y + lineWidth/2);
CGContextAddLineToPoint(context, endPoint.x + lineWidth/2, endPoint.y + lineWidth/2);
CGContextStrokePath(context);
CGContextRestoreGState(context);
NSLog(#"%f",_end.x);
}
- (void)setEnd:(CGPoint)end
{
_end = end;
[self setNeedsDisplay];
}
#end
drawRect: is only called when I initialize the view...
Draw method in UIViewController:
- (void)drawTLine:(CGPoint)start withEndPoint:(CGPoint)end
{
[[self dview] setStart:start];
[[self dview] setEnd:end];
[[self dview] drawRect:[self dview].frame];
}
This is how I add the drawing view:
DrawingView* dview = [[DrawingView alloc] initWithFrame:self.view.frame];
[dview setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:dview];
Subclass UIView and perform custom drawing using the drawRect: method
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetLineCap(context, kCGLineCapSquare);
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); //change color here
CGFloat lineWidth = 1.0; //change line width here
CGContextSetLineWidth(context, lineWidth);
CGPoint startPoint = rect.origin; //change start point here
CGPoint endPoint = {.x = CGRectGetMaxX(rect), .y = startPoint.y} //change end point here
CGContextMoveToPoint(context, startPoint.x + lineWidth/2, startPoint.y + lineWidth/2);
CGContextAddLineToPoint(context, endPoint.x + lineWidth/2, endPoint.y + lineWidth/2);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}
This will draw a black 1px line at the top of your UIView.
If you need to update the line you can just use some properties like
#property (nonatomic) CGPoint startPoint;
and provide a custom implementation for the setter like
- (void)setStartPoint:(CGPoint)point {
_point = point;
[self setNeedsDisplay]; // this will cause drawRect: to be called again
}
Do that for every property that you wish to control and make your drawRect: use such properties for drawing.
you can create and UIBezierPath like this
UIBezierPath path = [[UIBezierPath alloc] init]
[path moveToPoint: CGPoint(x,y)] // X and Y, start point
[path addLineToPoint:CGPoint(x2,y2) // X2 and Y2, end point
if you want to create a shape you can put more points with addLineToPoint: method and finish use
closePath method
I hope help you

Resources