📜  如何在 Android 应用中使用 Canvas API?

📅  最后修改于: 2022-05-13 01:55:04.455000             🧑  作者: Mango

如何在 Android 应用中使用 Canvas API?

Canvas API 也是 Android 中最常用的 API 之一。 API 本身的名称告诉我们该 API 正在用于在绘图板上绘图。借助此 API,我们可以绘制不同类型的形状并创建 Android 中不存在的自定义 UI 组件。在本文中,我们将了解 Canvas API 并在我们的应用程序中使用此 API 进行简单的设计。

什么是画布 API?

Canvas API 是 Android 中提供的绘图框架,借助它,我们可以在 UI 设计中创建自定义形状,例如矩形、圆形等。在这个 API 的帮助下,我们可以为我们的应用绘制任何类型的形状。不同形状的绘制是使用位图完成的。

了解 Canvas API 的工作原理

使用此 API 时,用户设备的屏幕称为 Canvas,我们必须在其上绘制不同类型的形状和设计。有不同的方法可用于在我们的 Canvas 上绘制不同的形状。以下是用于在 Canvas 上绘制形状的方法。

Methods

Description



onMeasure()

This method is used to measure the size of the view

and the children’s present in that view. 

onDraw()

This method is use to draw the different views in our Canvas. 

With this method we can draw different shapes on our Canvas. 

There are predefined methods for different shapes such as drawRect(),

drawArc(), drawLine() and many more.

onLayout()This method helps us to set the size of the view.

分步实施

第 1 步:创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Java作为编程语言。



步骤 2:使用 activity_main.xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。

XML




Java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.DisplayMetrics;
import android.view.View;
  
public class PaintView extends View {
      
    // below we are creating variables for our paint
    Paint otherPaint, outerPaint, textPaint;
     
    // and a floating variable for our left arc.
    float arcLeft;
  
    @SuppressLint("ResourceAsColor")
    public PaintView(Context context) {
        super(context);
          
        // on below line we are initializing our paint variable for our text
        textPaint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
          
        // on below line we are setting color to it.
        textPaint.setColor(Color.WHITE);
         
        // on below line we are setting text size to it.
        // In Paint we have to add text size using px so
        // we have created a method where we are converting dp to pixels.
        textPaint.setTextSize(pxFromDp(context, 24));
          
        // on below line we are initializing our outer paint
        outerPaint = new Paint();
          
        // on below line we are setting style to our paint.
        outerPaint.setStyle(Paint.Style.FILL);
          
        // on below line we are setting color to it.
        outerPaint.setColor(getResources().getColor(R.color.purple_200));
          
        // on below line we are creating a display metrics
        DisplayMetrics displayMetrics = new DisplayMetrics();
          
        // on below line we are getting display metrics.
        ((Activity) getContext()).getWindowManager()
                .getDefaultDisplay()
                .getMetrics(displayMetrics);
          
        // on below line we are assigning
        // the value to the arc left.
        arcLeft = pxFromDp(context, 20);
          
        // on below line we are creating 
        // a new variable for our paint
        otherPaint = new Paint();
    }
  
    // below method is use to generate px from DP.
    public static float pxFromDp(final Context context, final float dp) {
        return dp * context.getResources().getDisplayMetrics().density;
    }
  
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
          
        // below four lines of code is use to add
        // back color to our screen which is green
        canvas.drawPaint(outerPaint);
          
        // on below line we are setting color to our paint.
        otherPaint.setColor(Color.WHITE);
          
        // on below line we are setting style to out paint.
        otherPaint.setStyle(Paint.Style.FILL);
          
        // below 4 lines of code is use to
        // create white rectangle of screen
        canvas.drawRect(
                getLeft() + (getRight() - getLeft()) / 3,
                getTop() + (getBottom() - getTop()) / 3,
                getRight() - (getRight() - getLeft()) / 3,
                getBottom() - (getBottom() - getTop()) / 3, otherPaint);
          
        // on below line we are changing the color for our paint.
        otherPaint.setColor(getResources().getColor(R.color.purple_200));
          
        // on below line we are drawing a circle and passing 
        // width, height, left arc and paint to add color.
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, arcLeft, otherPaint);
          
        // on below line we are adding text using paint in our canvas.
        canvas.drawText("Geeks for Geeks", (float) (getWidth() * 0.3), (float) (getHeight() * 0.8), textPaint);
    }
}


Java
import android.os.Bundle;
import android.widget.RelativeLayout;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
      
    // creating a variable for our relative layout
    private RelativeLayout relativeLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our view.
        relativeLayout = findViewById(R.id.idRLView);
          
        // calling our  paint view class and adding 
        // its view to our relative layout.
        PaintView paintView = new PaintView(this);
        relativeLayout.addView(paintView);
    }
}


第 3 步:创建一个新的Java类来绘制我们的视图

导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Java类并将其命名为PaintView并将以下代码添加到其中。

Java

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.DisplayMetrics;
import android.view.View;
  
public class PaintView extends View {
      
    // below we are creating variables for our paint
    Paint otherPaint, outerPaint, textPaint;
     
    // and a floating variable for our left arc.
    float arcLeft;
  
    @SuppressLint("ResourceAsColor")
    public PaintView(Context context) {
        super(context);
          
        // on below line we are initializing our paint variable for our text
        textPaint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
          
        // on below line we are setting color to it.
        textPaint.setColor(Color.WHITE);
         
        // on below line we are setting text size to it.
        // In Paint we have to add text size using px so
        // we have created a method where we are converting dp to pixels.
        textPaint.setTextSize(pxFromDp(context, 24));
          
        // on below line we are initializing our outer paint
        outerPaint = new Paint();
          
        // on below line we are setting style to our paint.
        outerPaint.setStyle(Paint.Style.FILL);
          
        // on below line we are setting color to it.
        outerPaint.setColor(getResources().getColor(R.color.purple_200));
          
        // on below line we are creating a display metrics
        DisplayMetrics displayMetrics = new DisplayMetrics();
          
        // on below line we are getting display metrics.
        ((Activity) getContext()).getWindowManager()
                .getDefaultDisplay()
                .getMetrics(displayMetrics);
          
        // on below line we are assigning
        // the value to the arc left.
        arcLeft = pxFromDp(context, 20);
          
        // on below line we are creating 
        // a new variable for our paint
        otherPaint = new Paint();
    }
  
    // below method is use to generate px from DP.
    public static float pxFromDp(final Context context, final float dp) {
        return dp * context.getResources().getDisplayMetrics().density;
    }
  
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
          
        // below four lines of code is use to add
        // back color to our screen which is green
        canvas.drawPaint(outerPaint);
          
        // on below line we are setting color to our paint.
        otherPaint.setColor(Color.WHITE);
          
        // on below line we are setting style to out paint.
        otherPaint.setStyle(Paint.Style.FILL);
          
        // below 4 lines of code is use to
        // create white rectangle of screen
        canvas.drawRect(
                getLeft() + (getRight() - getLeft()) / 3,
                getTop() + (getBottom() - getTop()) / 3,
                getRight() - (getRight() - getLeft()) / 3,
                getBottom() - (getBottom() - getTop()) / 3, otherPaint);
          
        // on below line we are changing the color for our paint.
        otherPaint.setColor(getResources().getColor(R.color.purple_200));
          
        // on below line we are drawing a circle and passing 
        // width, height, left arc and paint to add color.
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, arcLeft, otherPaint);
          
        // on below line we are adding text using paint in our canvas.
        canvas.drawText("Geeks for Geeks", (float) (getWidth() * 0.3), (float) (getHeight() * 0.8), textPaint);
    }
}

第 4 步:使用MainActivity。 Java文件

转到主活动。 Java文件,参考如下代码。下面是MainActivity的代码。 Java文件。代码中添加了注释以更详细地理解代码。

Java

import android.os.Bundle;
import android.widget.RelativeLayout;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
      
    // creating a variable for our relative layout
    private RelativeLayout relativeLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our view.
        relativeLayout = findViewById(R.id.idRLView);
          
        // calling our  paint view class and adding 
        // its view to our relative layout.
        PaintView paintView = new PaintView(this);
        relativeLayout.addView(paintView);
    }
}

现在运行您的应用程序并查看应用程序的输出。

输出: