UIView的虚线边框

时间:2013-05-24 09:17:25

标签: objective-c uiview border

我需要为UIView添加虚线边框样式。我不想使用CGRectsetDash,因为您在设置后无法将其删除。我应该能够使用这种边框样式切换。我怎么得到它?

我有一个添加方法

-(void) addBorder
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [[UIColor blueColor] CGColor]);

    CGContextAddRect(context, self.bounds);
    CGContextStrokePath(context);
}

我收到错误'invalid context 0x0'

2 个答案:

答案 0 :(得分:1)

尝试以下方法,我的应用程序之一也具有相同的功能&我是按照以下方式完成的。

-(void)addDashedBorder
{
    //border definitions
    CGFloat cornerRadius = 0;
    CGFloat borderWidth = 1;
    NSInteger dashPattern1 = 4;
    NSInteger dashPattern2 = 4;
    UIColor *lineColor = [UIColor blackColor];

    //drawing
    CGRect frame = view.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
    [view.layer addSublayer:_shapeLayer];
    view.layer.cornerRadius = cornerRadius;
}

答案 1 :(得分:0)

在项目中添加QuartzCore/QuartzCore.h框架,并在#import <QuartzCore/QuartzCore.h>文件中导入.m

然后 尝试以下代码:

[view.layer setBorderWidth:5.0];
[view.layer setBorderColor:[[UIColor colorWithPatternImage:[UIImage imageNamed:@"DottedImage.png"]] CGColor]];

希望这会对你有所帮助。