使用CGContext绘制线条

12

我想在表格视图单元格中绘制线条,以便我可以在单个单元格中放置文本字段和开关。我增加了单元格的高度。如何在单元格中绘制线条?

我有一个UIView的子类,其中包含以下代码:

 //Get the CGContext from this view
 CGContextRef context = UIGraphicsGetCurrentContext();
 //Set the stroke (pen) color
 CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
 //Set the width of the pen mark
 CGContextSetLineWidth(context, 1.0);

 // Draw a line
 //Start at this point
 CGContextMoveToPoint(context, 10.0, 30.0);

 //Give instructions to the CGContext
 //(move "pen" around the screen)
 CGContextAddLineToPoint(context, 310.0, 30.0);


 //Draw it
 CGContextStrokePath(context);

我有一个使用分组表格样式的tableViewController。在cellForRowAtIndexPath中,我有以下代码:

//code to add textfield
DrawLineView *drawLine = [[DrawLineView alloc]init];
[cell addSubview:drawLine];
//code add switch

但是它没有画出任何线条。我不能使用两个不同的单元格。我必须请帮助我。这是我第一次处理 iPhone 上的图形。谢谢。

3个回答

20

如果你只想画一条直线,最好使用CAShapeLayer,并将其传递一个线的路径,然后将其附加为单元格内容视图的子层。这比使用带有自定义drawRect的视图在表格上执行更好。

通过CALayer和路径绘制直线的示例:

// You'll also need the QuartzCore framework added to the project
#import <QuartzCore/QuartzCore.h>

CAShapeLayer *lineShape = nil;
CGMutablePathRef linePath = nil;
linePath = CGPathCreateMutable();
lineShape = [CAShapeLayer layer];

lineShape.lineWidth = 4.0f;
lineShape.lineCap = kCALineCapRound;;
lineShape.strokeColor = [[UIColor blackColor] CGColor];

int x = 0; int y = 0;
int toX = 30; int toY = 40;                            
CGPathMoveToPoint(linePath, NULL, x, y);
CGPathAddLineToPoint(linePath, NULL, toX, toY);

lineShape.path = linePath;
CGPathRelease(linePath);
[self.layer addSublayer:lineShape];

你能解释一下怎么做吗? - iOSAppDev
使用CoreAnimation和CoreGraphics进行绘图似乎已经大量被抛弃。我刚刚观看了苹果在WDC2011上的一个视频,主持人注意到CoreGraphics比CoreAnimation更快。是否有可用于支持这些说法的基准测试? - Brian
1
我不太确定将CoreGraphics和CoreAnimation进行比较是否有意义,因为CoreGraphics是关于渲染图形的,而CoreAnimation是建立在其之上的,旨在随时间调整图形属性... 会议标题和名称是什么? - Kendall Helmstetter Gelner

0

有两件事情... 首先,通常不会直接在单元格中绘制。

通常会在内容视图中进行绘制。有时候也可以在单元格的backgroundView或selectedBackgroundView中进行绘制。

[cell.contentView addSubview:drawLine];

其次,默认单元格文本标签cell.textLabel和cell.detailTextLabel具有不透明的背景。尝试将它们的背景颜色设置为[UIColor clearColor]

编辑:还有一件事:您需要为您的drawLine设置适当的框架。

DrawLineView *drawLine = [[DrawLineView alloc]initWithFrame:cell.contentView.bounds];

0

我认为绘制一条线的非常简单的方法是创建一个UIView并填充所需的颜色,然后根据需要选择其宽度,并将高度设置为1像素,如下所示:

var lineView : UIView = {
     let view = UIView()
     view.backgroundColor = UIColor.blackColor()
     view.translatesAutoresizingMaskIntoConstraints = false
     return view
}()


self.view.addSubview(lineView)
self.view.addConstraints(NSLayoutConstraint.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": lineView])))
self.view.addConstraints(NSLayoutConstraint.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-50-[view(1)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": lineView])))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接