Android 绘图(一)——绘制直线的drawnline方法
功能: 此方法用于画布上绘制直线,通过制定两个端点的坐标进行绘制,这只能绘制单条直线,绘制多条是drawlines方法。
【基本语法】public void drawLine (float startX, float startY, float stopX, float stopY, Paint paint)
参数说明
startX:起始端点的X坐标。
startY:起始端点的Y坐标。
stopX:终止端点的X坐标。
stopY:终止端点的Y坐标。
paint:绘制直线所使用的画笔。
源码分析:
/**
* Draw a line segment with the specified start and stop x,y coordinates,
* using the specified paint.//使用指定的画笔,画一条指定好起止x,y坐标的线段
* <p>Note that since a line is always "framed", the Style is ignored in the paint.</p>//注意:因为线的样式已经定义了,风格在画笔中是被忽略的
* <p>Degenerate lines (length is 0) will not be drawn.</p>//简并线(长度为0)将不会被画出来
* @param startX The x-coordinate of the start point of the line//开始的X坐标点
* @param startY The y-coordinate of the start point of the line//开始的Y坐标点
* @param paint The paint used to draw the line//画线的画笔
*/
public void drawLine(float startX, float startY, float stopX, float stopY, Paint paint) {
native_drawLine(mNativeCanvas, startX, startY, stopX, stopY, paint.mNativePaint);
}
例子1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super .onDraw(canvas); paint.setColor(Color.BLACK); //设置画笔颜色 canvas.drawColor(Color.WHITE); //设置背景颜色 paint.setStrokeWidth((float) 1.0); //设置线宽 canvas.drawLine(50, 50, 450, 50, paint); //绘制直线 paint.setStrokeWidth((float) 5.0); //设置线宽 canvas.drawLine(50, 150, 450, 150, paint); //绘制直线 paint.setStrokeWidth((float) 10.0); //设置线宽 canvas.drawLine(50, 250, 450, 250, paint); //绘制直线 paint.setStrokeWidth((float) 15.0); //设置线宽 canvas.drawLine(50, 350, 450, 350, paint); //绘制直线 paint.setStrokeWidth((float) 20.0); //设置线宽 canvas.drawLine(50, 450, 450, 450, paint); //绘制直线 } |
例子2:下面是在绘制验证码线的时候的代码
获取直线的起止坐标:
public static int[] getLine(int height, int width)
{
int [] tempCheckNum = {0,0,0,0};
for(int i = 0; i < 4; i+=2)
{
tempCheckNum[i] = (int) (Math.random() * width);
tempCheckNum[i + 1] = (int) (Math.random() * height);
}
return tempCheckNum;
}
绘制直线:
int [] line;
for(int i = 0; i < ConmentConfig.LINE_NUM; i ++)
{
line = CheckGetUtil.getLine(height, width);
canvas.drawLine(line[0], line[1], line[2], line[3], mTempPaint);
}