Android绘图学习(一)

1.使用Canvas画布

在绘制图形图像的时候,需要先准备一张画布,也就是一张白纸,我们的图像将在这张白纸上绘制出来。在Android绘制二维图形应用中,类Canvas起了这张白纸的作用,也就是画布。在绘制过程中,所有产生的界面类都需要继承于该类。可以将画布类Canvas看作是一种处理过程,能够使用各种方法来管理Bitmap、GL或者Path路径。

Canvas():功能是创建一个空的画布,可以使用setBitmap()方法来设置绘制的具体画布。
Canvas画布比较重要,特别是在游戏开发应用中。例如可能需要对某个精灵执行旋转、缩放等操作时,需要通过旋转画布的方式实现。但是在旋转画布时会旋转画布上的所有对象,而我们只是需要旋转其中的一个,这时就需要用到save方法来锁定需要操作的对象,在操作之后通过restore方法来解除锁定。

2.使用paint类

有了画布之后,还需要用一支画笔来绘制图形图像。在Android系统中,绘制二维图形图像的画笔是类Paint。类Paint的完整写法是Android.Graphics.Paint,在里面定义了画笔和画刷的属性。在类Paint中的常用方法如下所示。
(1)void reset():实现重置功能。
(2)void setARGB(int a, int r, int g, int b)或void setColor(int color):功能是设置Paint对象的颜色。
(3)void setAntiAlias(boolean aa):功能是设置是否抗锯齿,此方法需要配合void setFlags (Paint.ANTI_ALIAS_FLAG)方法一起使用,来帮助消除锯齿使其边缘更平滑。
(4)Shader setShader(Shader shader):功能是设置阴影效果,Shader类是一个矩阵对象,如果为null则清除阴影。
(5)void setStyle(Paint.Style style):功能是设置样式,一般为Fill填充,或者STROKE凹陷效果。
(6)void setTextSize(float textSize):功能是设置字体的大小。
(7)void setTextAlign(Paint.Align align):功能是设置文本的对齐方式。
(8)Typeface setTypeface(Typeface typeface):功能是设置具体的字体,通过Typeface可以加载Android内部的字体,对于中文来说一般为宋体,我们可以根据需要来自己添加部分字体,例如雅黑等。
(9)void setUnderlineText(boolean underlineText):功能是设置是否需要下划线。

package com.example.game4shape;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;



public class MyView extends View {
    private float x=200;
    private float y=200;
    String a="hello world,用编程治愈生活,用技术影响世界";

    Paint paint=new Paint();

    public MyView(Context context) {
        super(context);


    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }




    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setAntiAlias(true);


        paint.setColor(Color.BLUE);
        paint.setTextSize(100);
        canvas.drawCircle(x,y,150, paint);

        canvas.drawText( a,x+200,y+400,paint);



        paint.setColor(Color.RED);
        canvas.drawRect(new Rect(15,15,150,70),paint);

    }

}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.game4shape.MyView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

03f55426c9084ded94cdef1bc9ea9f25.png

写在最后,手机坏了,截不了图。没坏之前复习了之前的40个单词。

猜你喜欢

转载自blog.csdn.net/qq_58259539/article/details/126092719#comments_26711142
今日推荐