个人公众号: ”安安安安卓“ 欢迎关注
Canvas使用
旋转
围绕指定点旋转
public final void rotate(float degrees, float px, float py)
围绕坐标原点旋转
public void rotate(float degrees)
平移
public void translate(float dx, float dy)
dx dy单位是像素
缩放
sx:x轴缩放的大小
sy:y轴缩放的大小
public void scale(float sx, float sy)
px:x轴的缩放点
py:y轴的缩放点
public final void scale(float sx, float sy, float px, float py)
保存和恢复
canvas.svae():保存画布
canvas.restore(): 释放画布
代码示例:
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.save()//保存画布
canvas?.translate(measuredWidth/2f,measuredHeight/2f)
for (i in 0..360 step 60){
canvas?.drawCircle(100f,0f,20f,paint)
canvas?.rotate(60f)
}
canvas?.restore()//释放画布
canvas?.drawCircle(100f,100f,100f,paint)
}
本例的代码中,save和restore中间的操作将画布移动到了屏幕中央,然后围绕屏幕中央绘制了六个圆。restore后canvas状态复原,再次画圆的参考点变为了左上角,圆绘制在了左上角
代码实现效果:
画圆
cx:圆心x坐标
cy:圆心y坐标
radius:圆半径
public void drawCircle(float cx, float cy, float radius, @NonNull Paint paint)
画线
startX:绘制起点x坐标
startY:绘制起点y坐标
stopX:绘制终点x坐标
stopY:绘制终点y坐标
一次绘制一条线
public void drawLine(float startX, float startY, float stopX, float stopY,
@NonNull Paint paint)
一次性绘制多条线
public void drawLines(@Size(multiple = 4) @NonNull float[] pts, int offset, int count,
@NonNull Paint paint)
绘制多个点的代码
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.translate(measuredWidth / 2f, measuredHeight / 2f)
val lines = floatArrayOf(-200f, 200f, 200f, 200f, 200f, -200f, -200f, -200f)
canvas?.drawLines(lines, paint)
}
这段代码的效果就是,绘制两条线:
第一条: (-200,200)--(200,200),
第二条线:(200,-200)--(-200,-200)
绘制效果
画椭圆
画椭圆需要构建一个RectF对象
RectF oval = new RectF(150, 200, 500, 400);// 画一个椭圆
canvas.drawOval(oval, p);
画弧形
api
public void drawArc(@NonNull RectF oval, float startAngle, float sweepAngle, boolean useCenter,
@NonNull Paint paint)
绘制代码
val oval = RectF(200f, 200f, 500f, 500f)
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawArc(oval, 0f, 120f, false, paint)
canvas?.translate(0f,400f)
canvas?.drawArc(oval, 0f, 120f, true, paint)
}
绘制效果
画矩形
api
public void drawRect(float left, float top, float right, float bottom, @NonNull Paint paint)
public void drawRoundRect(@NonNull RectF rect, float rx, float ry, @NonNull Paint paint)
绘制代码
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.apply {
drawRect(rect, paint)
translate(0f,500f)
drawRoundRect(rect,60f,80f,paint)
}
}
绘制效果
画多边形
通过Path绘制多边行,path篇有过介绍了
画贝塞尔曲线
通过Path绘制贝塞尔曲线,path篇有过介绍了
画点
api
绘制一个点
public void drawPoint(float x, float y, @NonNull Paint paint)
绘制多个点
public void drawPoints(@Size(multiple = 2) float[] pts, int offset, int count,
@NonNull Paint paint)
画图片
绘制图片代码
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawBitmap(bitmap, 300f, 300f, paint)
}
绘制效果