使用CGContext绘制线条
问题描述:
我想在表格视图单元格中画线,以便我可以将文本框&切换到单个单元格中。我增加了细胞的高度。我怎样才能在单元格中画线?使用CGContext绘制线条
我的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
但它没有画任何线。我不能使用2个不同的单元格。我必须请帮助我。这是我第一次处理图形iPhone。谢谢
答
两件事情... 首先,你通常不会吸入细胞本身。
您通常会进入内容视图。有时候,它有意义地绘制到单元格的backgroundView或selectedBackgroundView中。
[cell.contentView addSubview:drawLine];
二,默认的单元格文本标签cell.textLabel和cell.detailTextLabel具有非透明背景。尝试将其背景颜色设置为[UIColor clearColor]
。
编辑:一两件事:你需要设置一个适当的框架为您的drawLine
DrawLineView *drawLine = [[DrawLineView alloc]initWithFrame:cell.contentView.bounds];
答
如果你想要做的就是画一条线,这将是一个很大更好地使用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];
答
我认为画线的非常简化的方式是创建一个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])))
感谢您的回复。但它不工作。 – iOSAppDev 2011-03-20 18:59:32