Android 绘图常用API(Canvas Paint)

Paint:画笔类,用于设置颜色和样式.

Paint.Style

  • Paint.Style.FILL设置只绘制图形内容

  • Paint.Style.STROKE设置只绘制图形的边

  • Paint.Style.FILL_AND_STROKE设置都绘制

Shader

​ Shader is the based class for objects that return horizontal spans of colors during drawing. A subclass of Shader is installed in a Paint calling paint.setShader(shader). After that any object (other than a bitmap) that is drawn with that paint will get its color(s) from the shader.
Shader(着色器)是绘制时水平方向颜色对象的基类。它的子类将作为paint.setShader(shader)方法的参数。

当调用了paint.setShader(shader)之后,除了任何对象(除了bitmap)在用那个paint绘制时,都会从shader(着色器)中获得它的颜色

SweepGradient(扫描式渐变)

继承自Shader类.

//构造函数
public SweepGradient(float cx, float cy, @ColorInt int color0, @ColorInt int color1) {}
  • 构造1个围绕中心点绘制扫描渐变的着色器。
  • 参数cx,cy为中心点的座标,后2个参数分别为扫描的起点与终点的颜色

Canvas(翻译为画布)

1.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), and a paint (to describe the colors and styles for the drawing).
  • Canvas类有很多以draw开头的方法,也就是他可以画各种各样的图形
  • 要draw一个东西,需要4个基本的组件:
    • 要有1个Bitmap来保存像素
    • 1个canvas对象来调用draw方法,写入到上面的bitmap中
    • 要画的东西,比如矩形,路径,文本,Bitmap等
    • 最后还有1个Paint对象,用于描述颜色和样式风格

2.Canvas可以画哪些?

​ 弧线(arcs)、填充颜色(argb和color)、 Bitmap、圆(circle和oval)、点(point)、线(line)、矩形(Rect)、图片(Picture)、圆角矩形 (RoundRect)、文本(text)、顶点(Vertices)、路径(path)

2.1 drawArc()

public void drawArc(@NonNull RectF oval, float startAngle, float sweepAngle, boolean useCenter,@NonNull Paint paint )

第一个参数:RectF类(以浮点座标表示的矩形)

RectF mRectF = new Rect();
/*
 * left和top为矩形左上顶点的x和y座标
 * right和bottom为矩形右下顶点的x座标和y座标
 * 注意,原点是当前View的左上角顶点,而不一定是整个屏幕的左上角
 */
public void set(float left, float top, float right, float bottom) {
        ...
}

后面的参数

  • oval: 椭圆的边界,用于定义圆弧的形状和大小

  • startAngle : 弧的起始角度(时钟3点方向为0°,顺时针方向开始画)

  • sweepAngle:扫过的角度

  • useCenter:true表示会与矩形的中心点连接成为扇形,否则不会。这

  • paint: 画笔。如果Paint的Style为Stroke则没有扇形效果,只有一条弧线。

    举个栗子:

    canvas.drawArc(oval,-90,120,false,mPaint);
    

    设置Paint的Style为Stroke的效果

    设置Paint的Style为FILL的效果

    设置useCenter设置为true的效果:

注:sweepAngle >= 360时,效果都是画1个圆。

3.Canvas save() 和 restore()(保存和还原)

save()

  • 保存的是座标系的原点,座标轴的方向
  • 随后的平移,缩放,旋转,倾斜,concat或clipRect,clipPath调用都将照常运行,当后面调用restore()后,将会恢复到上一次save()时的状态,save()和restore()中间的调用将会被忘记

restore()

  • 恢复到上一次save()时的状态,resotre()调用次数比调用save()多时,将会发生错误

举个栗子:

//保存当前状态
canvas.save();
 //选择座标系
 canvas.rotate(mSweep, centerX, centerY);
//画圆弧
 canvas.drawArc(mRectF, 0, mSweep, true, mArcPaint);
//恢复到上次保存的状态
 canvas.restore();

4.Canvas旋转

public void rotate(float degrees) {...}
  • 将座标系选择指定角度,默认是View的左上角顶点水平正向为x轴正向,垂直下方向为y轴正向
public final void rotate(float degrees, float px, float py){...}
  • 以(px,py)为座标系中心,选择指定角度
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章