HJDashLineView.h
//
// HJDashLineView.h
// CGContextDemo
//
// Created by 黃健 on 16/7/18.
// Copyright © 2016年 黃健. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum : NSUInteger {
HJLineTypeDashLine,
HJLineTypeStraightLine
} HJLineType;
IB_DESIGNABLE
@interface HJDashLineView : UIView
// 如果不指定 lineType,默認繪製虛線,否則爲實線
@property (nonatomic, assign) IBInspectable BOOL lineType;
/**
線條寬度 lineWidth 默認 1
線條顏色 lineColor 默認 blackColor
偏移點數 movePoint 默認 0
繪製點數 drawPoint 默認 5
跳過點數 stepPoint 默認 3
當視圖寬大於高,水平虛線
當視圖高大於寬,豎直虛線
當視圖寬高相等,豎直虛線
*/
@property (nonatomic, assign) IBInspectable CGFloat lineWidth;
@property (nonatomic, strong) IBInspectable UIColor *lineColor;
@property (nonatomic, assign) IBInspectable CGFloat movePoint;
@property (nonatomic, assign) IBInspectable CGFloat drawPoint;
@property (nonatomic, assign) IBInspectable CGFloat stepPoint;
@end
HJDashLineView.m
//
// HJDashLineView.m
// CGContextDemo
//
// Created by 黃健 on 16/7/18.
// Copyright © 2016年 黃健. All rights reserved.
//
#import "HJDashLineView.h"
@implementation HJDashLineView
- (void)layoutSubviews
{
[super layoutSubviews];
// 由於設置的是直線或虛線,直接設置背景顏色爲透明
self.backgroundColor = [UIColor clearColor];
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
}
return self;
}
-(void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
CGFloat width = self.bounds.size.width;
CGFloat height = self.bounds.size.height;
if (width > height)
{
CGPathMoveToPoint(path, nil, 0, height / 2.f);
CGPathAddLineToPoint(path, nil, width, height / 2.f);
}
else
{
CGPathMoveToPoint(path, nil, width / 2.f, 0);
CGPathAddLineToPoint(path, nil, width / 2.f, height);
}
CGContextAddPath(context, path);
CGContextSetStrokeColorWithColor(context, self.lineColor ? self.lineColor.CGColor : [UIColor blackColor].CGColor);
CGContextSetLineWidth(context, self.lineWidth == 0 ? 1 : self.lineWidth);
if (self.lineType == HJLineTypeDashLine)
{
CGFloat lengths[2] = {self.drawPoint == 0 ? 5 : self.drawPoint, self.stepPoint == 0 ? 3 : self.stepPoint};
CGContextSetLineDash(context, self.movePoint == 0 ? 0 : -self.movePoint, lengths, 2);
}
CGContextDrawPath(context, kCGPathFillStroke);
}
- (void)setLineType:(BOOL)lineType
{
_lineType = lineType;
[self setNeedsDisplay];
}
- (void)setLineWidth:(CGFloat)lineWidth
{
_lineWidth = lineWidth;
[self setNeedsDisplay];
}
- (void)setLineColor:(UIColor *)lineColor
{
_lineColor = lineColor;
[self setNeedsDisplay];
}
- (void)setMovePoint:(CGFloat)movePoint
{
_movePoint = movePoint;
[self setNeedsDisplay];
}
- (void)setDrawPoint:(CGFloat)drawPoint
{
_drawPoint = drawPoint;
[self setNeedsDisplay];
}
- (void)setStepPoint:(CGFloat)stepPoint
{
_stepPoint = stepPoint;
[self setNeedsDisplay];
}
@end
Run