实际项目中需要画竖着的虚线,在网上没找到。。。就改造了一下画横着的虚线方法。
/**
* 画虚线
*
* @param frame 虚线的frame
* @param isTrans 是否要旋转(画竖线则为YES,横线则为NO)
*/
(void)shapeLineWithFrame:(CGRect)frame isTrans:(BOOL)isTrans{
UIImageView *imageView = [[UIImageView alloc]initWithFrame:frame];
imageView.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:imageView];
if (isTrans) {
CGRect rect = CGRectMake(CGRectGetMinX(imageView.frame)-(imageView.frame.size.height-imageView.frame.size.width)/2.0, CGRectGetMinY(imageView.frame)+(imageView.frame.size.height-imageView.frame.size.width)/2.0, imageView.frame.size.height, imageView.frame.size.width);
imageView.frame = rect;
}
UIGraphicsBeginImageContext(imageView.frame.size); //开始画线
[imageView.image drawInRect:CGRectMake( 0, 0, CGRectGetWidth(imageView.frame), CGRectGetHeight(imageView.frame))];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); //设置线条终点形状
CGFloat lengths[] = {3,3};
CGContextRef line = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(line, [UIColor lightGrayColor].CGColor);
CGContextSetLineDash(line, 0, lengths, 2); //画虚线
CGContextMoveToPoint(line, 0, 0); //开始画线
CGContextAddLineToPoint(line, CGRectGetMaxX(imageView.frame), 0);
CGContextStrokePath(line);
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
if (isTrans) {
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI_2);
imageView.transform = transform;
}
}
当参数isTrans为YES的时候,计算出竖线所对应的横线的frame(计算出以竖线的中心为原点旋转90°之后的frame),先画出横线,最后旋转90°(M_PI_2)即可;为NO时直接画虚线即可。
方法解释:
void CGContextSetLineDash (
CGContextRef _Nullable c, //图形上下文 (可以理解为”画板“)
CGFloat phase, //从多少单位(多远)开始画虚线
const CGFloat * _Nullable
lengths, //线和空格的长度数组
size_t count //想要取的数组参数中元素的个数
); //设置怎么画void CGContextMoveToPoint (
CGContextRef _Nullable c, //图形上下文
CGFloat x, //x坐标
CGFloat y //y坐标
); //从指定的点开始画void CGContextAddLineToPoint (
CGContextRef _Nullable c, //图形上下文
CGFloat x, //终点x坐标
CGFloat y //终点y坐标
); // 设置终点void CGContextStrokePath (
CGContextRef _Nullable c
); // 在”画板“上画线