在ios中创建水平虚线

时间:2014-03-27 11:58:42

标签: ios objective-c

我想绘制一条直线虚线,我尝试了以下代码

    CGSize size = CGSizeMake(screenWidth, screenHeight);
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);    
    CGContextSetLineWidth(context, 5.0f);
    CGContextMoveToPoint(context, 0, 0);
    CGContextAddLineToPoint(context, screenWidth,screenHeight);
    CGContextStrokePath(context);

但是此代码显示如下

enter image description here

我怎样才能得到直线。

3 个答案:

答案 0 :(得分:4)

您可以使用

void CGContextSetLineDash (
   CGContextRef c,
   CGFloat phase,
   const CGFloat lengths[],
   size_t count
);

说明

  

在图形上下文中设置虚线的模式。

所以你的代码应该改为

CGSize size = CGSizeMake(screenWidth, screenHeight);
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);    
CGContextSetLineWidth(context, 5.0f);

// Because your line width is 5 you need pattern 5 times “solid”, 5 times “empty”
CGFloat dash[2]={5 ,5};
CGContextSetLineDash(context,0,dash,2);

CGFloat y = 10;

CGContextMoveToPoint(context, 0, y);
CGContextAddLineToPoint(context, screenWidth, y);
CGContextStrokePath(context);

答案 1 :(得分:2)

你应该使用核心图形,这段代码会创建一条虚线,你可以在其中设置线条和空间的长度

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        [shapeLayer setBounds:self.bounds];
        [shapeLayer setPosition:self.center];
        [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
        [shapeLayer setStrokeColor:[[UIColor grayColor] CGColor]];
        [shapeLayer setLineWidth:1.0f];
        [shapeLayer setLineJoin:kCALineJoinRound];
        [shapeLayer setLineDashPattern:@[@5., @3.]];


        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, NULL, -15, 5);
        CGPathAddLineToPoint(path, NULL, 1030, 5);

        [shapeLayer setPath:path];
        CGPathRelease(path);

        [[self layer] addSublayer:shapeLayer];

答案 2 :(得分:0)

您的问题可能不是渲染图像,而是您呈现它的方式。在UIImage上设置UIImageView时,请确保它们具有相同的比例:

UIImageView *line; // your image view
UIImage *result;   // the rendered image

line.bounds = (CGRect){.size=result.size};
相关问题