i want to make the border of a UIView to be like a wave and i just can't get it out how.
I have tried just to draw a wave line with a code found here, but it just don't work
CGRect rect = CGRectMake(100, 100, 500, 500);
self.heightCrest = 30;
float w = 0; // starting position
float y = rect.size.height;
float width = rect.size.width;
int cycles = 7;//number of waves
self.x = width/cycles;
CGContextRef context = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
while (w<width) {
CGPathMoveToPoint(path, NULL, w,y/2);
CGPathAddQuadCurveToPoint(path, NULL, w+self.x/4, y/2 - self.heightCrest, w+self.x/2, y/2);
CGPathAddQuadCurveToPoint(path, NULL, w+3*self.x/4, y/2 + self.heightCrest, w+self.x, y/2);
w+=self.x;
}
CGContextAddPath(context, path);
CGContextDrawPath(context, kCGPathStroke);
try like this:
- (void)addHorizontalDownwardCurveToPath:(UIBezierPath *)path toPoint:(CGPoint)point withAmplitude:(CGFloat)amplitude {
CGFloat middle = (point.x + path.currentPoint.x) / 2;
[path addQuadCurveToPoint:point
controlPoint:CGPointMake(middle, point.y + amplitude)];
}
Related
I draw a wave layer by override drawInContext:(CGContextRef)ctx method,since the wave line is sine-wave ,so I cut it into segments by calculate wave value and join them into CGMutablePathRef
Here is what I have done in -(void)drawInContext:(CGContextRef)ctx
//join style
CGContextSetLineJoin(ctx, kCGLineJoinRound);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetAllowsAntialiasing(ctx, true);
CGContextSetShouldAntialias(ctx, true);
CGContextSetFillColorWithColor(ctx, [UIColor themeColor].CGColor);
CGContextSetStrokeColorWithColor(ctx, [UIColor themeColor].CGColor);
CGContextSaveGState(ctx);
CGMutablePathRef mutablePath = CGPathCreateMutable();
CGPathMoveToPoint(mutablePath, NULL, 0, 0);
CGPathAddLineToPoint(mutablePath, NULL, 0, [self getSinPoint:0 WaveHeight:self.waveHeight]);
//Calculate the Sin funciton value to draw lines and join them into path
for (float i = 0; i <= self.bounds.size.width; i+= 1) {
NSInteger pointY = [self getSinPoint:i WaveHeight:self.waveHeight];
CGPathAddLineToPoint(mutablePath, NULL, i, pointY);
}
CGPathAddLineToPoint(mutablePath, NULL, self.bounds.size.width, 0);
CGPathCloseSubpath(mutablePath);
[[UIColor themeColor]set];
CGContextAddPath(ctx, mutablePath);
CGContextFillPath(ctx);
CGContextRestoreGState(ctx);
One solution is using BezierPath to draw the wave,
1.cut the line into segment such as 20
2.if current line index is event, get the control point below the center of the current segment
3.if current line index is odd,then get the control point up the center of the line
...
for (NSInteger i = 0; i <= self.waveCount; i++) {
CGPoint beginPoint = CGPointMake(i * self.waveWidth, pointY);
CGPoint endPoint = CGPointMake((i + 1) * self.waveWidth, pointY);
if (i%2 == 0) {
CGPoint controlPoint = [self getCenterControlPointUp:beginPoint End:endPoint];
CGPathAddQuadCurveToPoint(mutablePath, NULL, controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
}else{
CGPoint controlPoint = [self getCenterControlPointDown:beginPoint End:endPoint];
CGPathAddQuadCurveToPoint(mutablePath, NULL, controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
}
}
...
method to get the control point of a segment line
//Below
-(CGPoint)getCenterControlPointDown:(CGPoint)begin End:(CGPoint)end{
return CGPointMake((begin.x + end.x)/2, (begin.y + end.y)/2 + self.waveHeight * 2);
}
//Above
-(CGPoint)getCenterControlPointUp:(CGPoint)begin End:(CGPoint)end{
return CGPointMake((begin.x + end.x)/2, (begin.y + end.y)/2 - self.waveHeight * 2);
}
I'm developing a Augmented reality app where I need to add a 3D grid on camera overlay. My attempt so far:
DrawLayer.h
#import <UIKit/UIKit.h>
#interface DrawLayer : UIView
#property (nonatomic, assign) int numberOfColumns;
#property (nonatomic, assign) int numberOfRows;
#end
DrawLayer.m
#import "DrawLayer.h"
#implementation DrawLayer
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 0.5);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
// ---------------------------
// Drawing column lines
// ---------------------------
// calculate column width
CGFloat columnWidth = self.frame.size.width / (self.numberOfColumns + 1.0);
for(int i = 1; i <= self.numberOfColumns; i++)
{
CGPoint startPoint;
CGPoint endPoint;
startPoint.x = columnWidth * i;
startPoint.y = 0.0f;
endPoint.x = startPoint.x;
endPoint.y = self.frame.size.height;
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
CGContextStrokePath(context);
}
// ---------------------------
// Drawing row lines
// ---------------------------
// calclulate row height
CGFloat rowHeight = self.frame.size.height / (self.numberOfRows + 1.0);
for(int j = 1; j <= self.numberOfRows; j++)
{
CGPoint startPoint;
CGPoint endPoint;
startPoint.x = 0.0f;
startPoint.y = rowHeight * j;
endPoint.x = self.frame.size.width;
endPoint.y = startPoint.y;
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
CGContextStrokePath(context);
}
}
#end
And Adding it to a camera overlay
DrawLayer *gridView = [[DrawLayer alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
gridView.backgroundColor=[UIColor clearColor];
gridView.numberOfColumns = 10;
gridView.numberOfRows = 8;
[gridView setNeedsDisplay];
CATransform3D t=gridView.layer.transform;
t.m34 = 1.0 / -300.0;
t = CATransform3DRotate(t, DEGREES_TO_RADIANS(60.0), 1, 0, 0);
gridView.layer.transform=t;
[cameraUI setCameraOverlayView:gridView];
Now My result is :
But I want the output like this:
Whats wrong with this code? Please help.
I'm creating a dotted line from a UIBezierPath which looks like this:
This is the code I use to construct and draw the path:
const CGContextRef context = UIGraphicsGetCurrentContext();
const CGSize visibleSize = CGSizeMake(self.width - (kIndent * 2), self.height - (kIndent * 2));
UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(kIndent, kIndent, visibleSize.width, visibleSize.height) cornerRadius:kCornerRadius];
CGContextSetStrokeColorWithColor(context, [UIColor colorWithWhite:1.0 alpha:0.5].CGColor);
[borderPath setLineWidth:2.0];
[borderPath setLineCapStyle:kCGLineCapRound];
const CGFloat pattern[] = {6, 6};
[borderPath setLineDash:pattern count:2 phase:0];
[borderPath stroke];
What I want is for each corner of my square to have the exact same curvatures as each other. I know this will ultimately be determined by my pattern values. I have tried calculating different values from the width of the shape (the width changes with screen width), but I can't get my desired look.
Has anyone done this before, or have any ideas to share about how I'd do this?
This is what I done before. Not perfect but I think this can help you.
- (void)tailorRect:(CGRect)aRect dotsWidth:(CGFloat)dotWidth radius:(CGFloat)radius withColor:(UIColor*)color{
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSaveGState(c);
CGFloat minSpacing = 10;
CGFloat mWidth = aRect.size.width - radius *2;
CGFloat mHeight = aRect.size.height - radius *2;
int countW = mWidth / (dotWidth + minSpacing);
int countH = mHeight / (dotWidth + minSpacing);
CGFloat spacingW = (mWidth - (dotWidth * countW)) / (countW + 1);
CGFloat spacingH = (mHeight -(dotWidth * countH)) / (countH + 1);
CGContextSetLineCap(c, kCGLineCapRound);
CGContextSetLineWidth(c, 1.2);
CGRect tempRect = aRect;
for (int r = 0; r<=1; r++)
{
if (r==0)
{
CGContextSetStrokeColorWithColor(c, [[UIColor whiteColor] colorWithAlphaComponent:0.9].CGColor);
aRect = CGRectOffset(tempRect, 0, 0.5);
}
else
{
CGContextSetStrokeColorWithColor(c, color.CGColor);
aRect = tempRect;
}
for (int w = 0; w<=1; w++)
{
CGFloat y = (w==0) ? aRect.origin.y : CGRectGetMaxY(aRect);
CGPoint pointsW[countW*2];
for (int i = 0; i<countW*2; i++)
{
CGFloat x;
CGFloat startPointX = radius + spacingW +aRect.origin.x;
if (i%2 != 0)
{
x = startPointX
+ dotWidth * (i+1)/ 2
+ spacingW * ((int)i/2);
}
else
{
x = startPointX
+ (dotWidth+spacingW) * ((int)i/2);
}
pointsW[i] = CGPointMake(x, y);
}
CGContextStrokeLineSegments(c, pointsW, countW*2);
}
for (int h = 0; h<=1; h++)
{
CGFloat x = (h==0) ? aRect.origin.x : CGRectGetMaxX(aRect);
CGPoint pointsH[countH*2];
for (int j = 0; j<countH*2; j++)
{
CGFloat startY = radius + spacingH + aRect.origin.y;
CGFloat y;
if (j%2 != 0)
{
y = startY + dotWidth * (j+1)/2 + spacingH * ((int)j/2);
}
else
{
y = startY + (dotWidth + spacingH) * ((int)j/2);
}
pointsH[j] = CGPointMake(x, y);
}
CGContextStrokeLineSegments(c, pointsH, countH*2);
}
//radius
for (int i = 0; i<4; i++)
{
CGPoint point0;
CGPoint point1;
CGPoint point2;
switch (i) {
case 0:
point0 = CGPointMake(CGRectGetMinX(aRect), CGRectGetMinY(aRect) + radius);
point1 = CGPointMake(CGRectGetMinX(aRect), CGRectGetMinY(aRect));
point2 = CGPointMake(CGRectGetMinX(aRect) + radius, CGRectGetMinY(aRect));
break;
case 1:
point0 = CGPointMake(CGRectGetMaxX(aRect) - radius, CGRectGetMinY(aRect));
point1 = CGPointMake(CGRectGetMaxX(aRect), CGRectGetMinY(aRect));
point2 = CGPointMake(CGRectGetMaxX(aRect) , CGRectGetMinY(aRect) +radius);
break;
case 2:
point0 = CGPointMake(CGRectGetMaxX(aRect), CGRectGetMaxY(aRect) - radius);
point1 = CGPointMake(CGRectGetMaxX(aRect), CGRectGetMaxY(aRect));
point2 = CGPointMake(CGRectGetMaxX(aRect) - radius, CGRectGetMaxY(aRect));
break;
case 3:
point0 = CGPointMake(CGRectGetMinX(aRect), CGRectGetMaxY(aRect) - radius);
point1 = CGPointMake(CGRectGetMinX(aRect), CGRectGetMaxY(aRect));
point2 = CGPointMake(CGRectGetMinX(aRect) + radius, CGRectGetMaxY(aRect));
break;
default:
break;
}
CGContextMoveToPoint(c, point0.x, point0.y);
CGContextAddArcToPoint(c, point1.x, point1.y, point2.x, point2.y, radius);
CGContextStrokePath(c);
}
}
CGContextRestoreGState(c);
}
It's very simple:
[yourView.layer setBorderWidth:5.0];
[yourView.layer setBorderColor:[[UIColor colorWithPatternImage:[UIImage imageNamed:#"DotedImage.png"]] CGColor]];///just add image name and create image with dashed or doted drawing and add here
Here you're just required to add QuartzCore/QuartzCore.h framework in project and import it as below in .m file
#import <QuartzCore/QuartzCore.h>
Or try using
- (void)drawDashedBorderAroundView:(UIView *)v
{
//border definitions
CGFloat cornerRadius = 10;
CGFloat borderWidth = 2;
NSInteger dashPattern1 = 8;
NSInteger dashPattern2 = 8;
UIColor *lineColor = [UIColor orangeColor];
//drawing
CGRect frame = v.bounds;
CAShapeLayer *_shapeLayer = [CAShapeLayer layer];
//creating a path
CGMutablePathRef path = CGPathCreateMutable();
//drawing a border around a view
CGPathMoveToPoint(path, NULL, 0, frame.size.height - cornerRadius);
CGPathAddLineToPoint(path, NULL, 0, cornerRadius);
CGPathAddArc(path, NULL, cornerRadius, cornerRadius, cornerRadius, M_PI, -M_PI_2, NO);
CGPathAddLineToPoint(path, NULL, frame.size.width - cornerRadius, 0);
CGPathAddArc(path, NULL, frame.size.width - cornerRadius, cornerRadius, cornerRadius, -M_PI_2, 0, NO);
CGPathAddLineToPoint(path, NULL, frame.size.width, frame.size.height - cornerRadius);
CGPathAddArc(path, NULL, frame.size.width - cornerRadius, frame.size.height - cornerRadius, cornerRadius, 0, M_PI_2, NO);
CGPathAddLineToPoint(path, NULL, cornerRadius, frame.size.height);
CGPathAddArc(path, NULL, cornerRadius, frame.size.height - cornerRadius, cornerRadius, M_PI_2, M_PI, NO);
//path is set as the _shapeLayer object's path
_shapeLayer.path = path;
CGPathRelease(path);
_shapeLayer.backgroundColor = [[UIColor clearColor] CGColor];
_shapeLayer.frame = frame;
_shapeLayer.masksToBounds = NO;
[_shapeLayer setValue:[NSNumber numberWithBool:NO] forKey:#"isCircle"];
_shapeLayer.fillColor = [[UIColor clearColor] CGColor];
_shapeLayer.strokeColor = [lineColor CGColor];
_shapeLayer.lineWidth = borderWidth;
_shapeLayer.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:dashPattern1], [NSNumber numberWithInt:dashPattern2], nil];
_shapeLayer.lineCap = kCALineCapRound;
//_shapeLayer is added as a sublayer of the view, the border is visible
[v.layer addSublayer:_shapeLayer];
v.layer.cornerRadius = cornerRadius;
}
You can have some study in
http://lukagabric.com/cashapelayer-example-round-corners-view-with-dashed-line-border/
https://github.com/lukagabric/LBorderView
drawing dashed line using CALayer
UIView with a Dashed line
Here is a UIView subclass that can work for any project, it also works for round views:
import UIKit
class CustomDashedView: UIView {
#IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
#IBInspectable var dashWidth: CGFloat = 0
#IBInspectable var dashColor: UIColor = .clear
#IBInspectable var dashLength: CGFloat = 0
#IBInspectable var betweenDashesSpace: CGFloat = 0
var dashBorder: CAShapeLayer?
override func layoutSubviews() {
super.layoutSubviews()
dashBorder?.removeFromSuperlayer()
let dashBorder = CAShapeLayer()
dashBorder.lineWidth = dashWidth
dashBorder.strokeColor = dashColor.cgColor
dashBorder.lineDashPattern = [dashLength, betweenDashesSpace] as [NSNumber]
dashBorder.frame = bounds
dashBorder.fillColor = nil
if cornerRadius > 0 {
dashBorder.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
} else {
dashBorder.path = UIBezierPath(rect: bounds).cgPath
}
layer.addSublayer(dashBorder)
self.dashBorder = dashBorder
}
}
This way you can edit from the Storyboard like this:
I am trying to create the circles below in my iOS app. I know how to make the circles but am not entirely sure on how to get the points along the arc. It has to be in code not an image. Below is also the code I currently have.
- (void)drawRect:(CGRect)rect
{
CGPoint point;
point.x = self.bounds.origin.x + self.bounds.size.width/2;
point.y = self.bounds.origin.y + self.bounds.size.height/2;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGRect circle = CGRectMake(point.x/2,point.y-point.x/2,point.x,point.x);
CGContextAddEllipseInRect(context, circle);
CGContextStrokePath(context);
for (int i = 0; i<8; i++) {
CGRect circleMini = CGRectMake(??????,??????,point.x/4,point.x/4);
CGContextAddEllipseInRect(context, circleMini);
CGContextStrokePath(context);
}
}
UPDATED TO ANSWER
float cita = 0;
for (int i = 0; i<8; i++) {
CGPoint pointCir = CGPointMake(point.x/2 + radius * cos(cita) , (point.y-point.x/2) + radius * sin(cita) );
CGRect circleMini = CGRectMake(pointCir.x,pointCir.y,radius/4,radius/4);
CGContextAddEllipseInRect(context, circleMini);
CGContextStrokePath(context);
cita += M_PI / 4.0;
}
If (x,y) is the center and r is the radius of your big circle, the center of the i-th external circle will be:
center(i) = ( x + r * cos(cita) , y + r * sin(cita) )
Start cita in 0 and increment it PI/4 radians for the next circle (or 45 degrees)
Working implementation
CGFloat cita = 0;
CGFloat bigCircleRadius = point.x / 2.0;
CGFloat smallCircleRadius = bigCircleRadius / 4.0;
for (int i = 0; i < 8; i++) {
CGPoint smallCircleCenter = CGPointMake(point.x + bigCircleRadius * cos(cita) - smallCircleRadius/2.0 , point.y + bigCircleRadius * sin(cita) - smallCircleRadius / 2.0 );
CGRect smallCircleRect = CGRectMake(smallCircleCenter.x,smallCircleCenter.y,smallCircleRadius,smallCircleRadius);
CGContextAddEllipseInRect(context, smallCircleRect);
CGContextStrokePath(context);
cita += M_PI / 4.0;
}
Edit: Added implementation and renamed variables.
- (void)drawRect:(CGRect)rect
{
const NSUInteger kNumCircles = 8u;
CGFloat height = CGRectGetHeight(rect);
CGFloat smallCircleRadius = height / 10.0f;
CGRect bigCircleRect = CGRectInset(rect, smallCircleRadius / 2.0f, smallCircleRadius / 2.0f);
CGFloat bigCircleRadius = CGRectGetHeight(bigCircleRect) / 2.0f;
CGPoint rectCenter = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0f);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextAddEllipseInRect(context, bigCircleRect);
CGContextStrokePath(context);
CGFloat alpha = 0;
for (NSUInteger i = 0; i < kNumCircles; i++)
{
CGPoint smallCircleCenter = CGPointMake(rectCenter.x + bigCircleRadius * cos(alpha) - smallCircleRadius/2.0f , rectCenter.y + bigCircleRadius * sin(alpha) - smallCircleRadius / 2.0f );
CGRect smallCircleRect = CGRectMake(smallCircleCenter.x,smallCircleCenter.y,smallCircleRadius,smallCircleRadius);
CGContextAddEllipseInRect(context, smallCircleRect);
CGContextStrokePath(context);
alpha += M_PI / (kNumCircles / 2.0f);
}
}
I'm trying to find a way to display the borders of some CGRects in my iOS program for debugging purposes. Is there a fairly simple way to do this? I just need to see where the program is creating these rectangles, so I can track down some odd touch behaviors (or lack thereof).
My class init method:
// Initialize with points and a line number, then draw a rectangle
// in the shape of the line
-(id)initWithPoint:(CGPoint)sP :(int)w :(int)h :(int)lN :(int)t {
if ((self = [super init])) {
startP = sP;
lineNum = lN;
width = w;
height = h;
int type = t;
self.gameObjectType = kPathType;
// Draw the path sprite
path = [CCSprite spriteWithFile: #"line.png" rect:CGRectMake(0, 0, 5, height)];
ccTexParams params = {GL_LINEAR,GL_LINEAR,GL_REPEAT,GL_REPEAT};
[path.texture setTexParameters:¶ms];
if(type == 1) {
path.position = ccp(startP.x, startP.y);
} else {
path.rotation = 90;
path.anchorPoint = ccp(0, 0);
path.position = ccp(startP.x, startP.y-2);
}
[self addChild:path];
// Draw the "bounding" box
pathBox = CGRectMake(path.position.x - (path.contentSize.width/2), path.position.y - (path.contentSize.height/2), path.contentSize.width * 10, path.contentSize.height);
}
return self;
}
pathBox is the rect in question.
This can be handled within drawRect:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect aRect=[myPath bounds];
CGContextSetLineWidth(context, 2);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor ].CGColor);
CGContextStrokeRect(context, aRect);
}
I'm going to take a stab and assume this is an iOS project, since that's what I know.
If these rectangles are being used for UIView or a CALayer then you can set the border for them.
Add #import <QuartzCore/QuartzCore.h> in your file and use view.layer.borderColor, view.layer.borderWidth add what you want.
If it's just a layer remove the view part of it.
I figured out more-or-less how to do it: just extended the draw method in my class like so:
-(void) draw {
glColor4f(0, 1.0, 0, 1.0);
glLineWidth(2.0f);
[super draw];
CGRect pathBox = CGRectMake(path.position.x - (path.contentSize.width/2), path.position.y - (path.contentSize.height/2), path.contentSize.width * 10, path.contentSize.height);
CGPoint verts[4] = {
ccp(pathBox.origin.x, pathBox.origin.y),
ccp(pathBox.origin.x + pathBox.size.width, pathBox.origin.y),
ccp(pathBox.origin.x + pathBox.size.width, pathBox.origin.y + pathBox.size.height),
ccp(pathBox.origin.x, pathBox.origin.y + pathBox.size.height)
};
ccDrawPoly(verts, 4, YES);
}
Thanks to Blue Ether over at the Cocos2D site for the heads-up:
http://www.cocos2d-iphone.org/forum/topic/21718?replies=5#post-120691
You can try something simple like this method here. This uses an actual CGRect structure as oppose to a UIView and CLayer.
-(void) drawBorderForRect:(CGRect)rect usingColor:(UIColor*)uiColor{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, uiColor.CGColor);
CGContextSetLineWidth(context, 1.0f);
CGFloat x = rect.origin.x;
CGFloat y = rect.origin.y;
CGFloat width = abs(rect.size.width);
CGFloat height = abs(rect.size.height);
// ---
CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(context, x + width, y);
// |
CGContextMoveToPoint(context, x + width, y);
CGContextAddLineToPoint(context, x + width, y - height);
// ---
CGContextMoveToPoint(context, x + width, y - height);
CGContextAddLineToPoint(context, x - width, y - height);
// |
CGContextMoveToPoint(context, x, y - height);
CGContextAddLineToPoint(context, x, y);
CGContextStrokePath(context);
}
In swift, it's easy. You can construct a BezierPath from a CGRect:
let dp = UIBezierPath.init(rect: myRect)
dp.stroke()