Paint(画笔)
Canvas(画布)
The Canvas class holds the "draw" calls.
To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), anda paint (to describe the colors and styles for the drawing).
- rotate(float degrees,float px,float py)//对canvas执行旋转变换
scale(float sx,float sy)//对canvas执行缩放
skew(float sx,float sy)//对canvas执行倾斜变换
translate(float dx,float dy)//移动canvas,向右dx,向下dy
- //
- setBitmap(Bitmap bitmap)
Path(绘画路径)
预先在View上将N个点连成一条“路径”,然后调用Canvas的drawPath(path,paint)即可沿着路径绘制图形
//Path
moveTo(float x,float y)//Set the beginning of the next contour to the point (x,y).
lineTo(float x,float y)//Add a line from the last point to the specified point (x,y).
//canvas
drawTextOnPath(String text, Path path, float hOffset, float vOffset, Paint paint)//
hOffset水平偏移 vOffset垂直偏移
Android还为路径绘制提供了PathEffect来定义绘制效果,PathEffect包含如下子类:
ComposePathEffect CornerPathEffect DashPathEffect DiscretePathEffect PathDashPathEffect SumPathEffect
- Paint paint =newPaint();
paint.setPathEffect(PathEffect effect);
实例:采用双缓冲实现画图板
publicclassDrawView extends View
{
// 定义记录前一个拖动事件发生点的坐标
float preX;
float preY;
privatePath path;
publicPaint paint = null;
// 定义一个内存中的图片,该图片将作为缓冲区
Bitmap cacheBitmap = null;
// 定义cacheBitmap上的Canvas对象
Canvas cacheCanvas = null;
publicDrawView(Context context,int width ,int height)
{
super(context);
// 创建一个与该View相同大小的缓存区
cacheBitmap =Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
cacheCanvas =newCanvas();
path =newPath();
// 设置cacheCanvas将会绘制到内存中的cacheBitmap上
cacheCanvas.setBitmap(cacheBitmap);
// 设置画笔的颜色
paint =newPaint(Paint.DITHER_FLAG);
paint.setColor(Color.RED);
// 设置画笔风格
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
// 反锯齿
paint.setAntiAlias(true);
paint.setDither(true);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
// 获取拖动事件的发生位置
float x = event.getX();
float y = event.getY();
switch(event.getAction())
{
caseMotionEvent.ACTION_DOWN:
// 从前一个点绘制到当前点之后,把当前点定义成下次绘制的前一个点
path.moveTo(x, y);
preX = x;
preY = y;
break;
caseMotionEvent.ACTION_MOVE:
// 从前一个点绘制到当前点之后,把当前点定义成下次绘制的前一个点
path.quadTo(preX, preY, x, y);
preX = x;
preY = y;
break;
caseMotionEvent.ACTION_UP:
cacheCanvas.drawPath(path, paint);// ①
path.reset();
break;
}
invalidate();
// 返回true表明处理方法已经处理该事件
returntrue;
}
@Override
publicvoid onDraw(Canvas canvas)
{
Paint bmpPaint =newPaint();
// 将cacheBitmap绘制到该View组件上
canvas.drawBitmap(cacheBitmap,0,0, bmpPaint);// ②
// 沿着path绘制
canvas.drawPath(path, paint);
}
}
整理自:《疯狂Android讲义》