2

我需要为UIView. 我不想使用CGRectsetDash因为您在设置后无法删除它。我应该能够使用这种边框样式进行切换。我该如何解决?

我有一个方法可以添加

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

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

我收到错误“无效的上下文 0x0”

4

2 回答 2

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;
}
于 2013-05-24T09:32:55.780 回答
0

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

然后尝试以下代码:

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

希望这对您有所帮助。

于 2013-05-24T09:24:02.857 回答