📜  如何使用 Kotlin 在 Android 中画一条线?

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

如何使用 Kotlin 在 Android 中画一条线?

在 Android 中,Canvas 是一个在 Bitmap 上的二维空间(屏幕上的 X 和 Y)中执行绘图的类。然后可以使用 ImageView 显示此位图。在本文中,我们将向您展示如何使用画布绘制线条,将它们存储在 Bitmap 上并在 Android 中的 ImageView 中显示。 IDE 准备就绪后,请按照以下步骤操作。

分步实施

第 1 步:在 Android Studio 中创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。我们在Kotlin中演示了该应用程序,因此请确保在创建新项目时选择 Kotlin 作为主要语言。

第 2 步:使用 activity_main.xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是activity_main.xml文件的代码。添加一个 ImageView,如下所示。

XML


  
    
  


Kotlin
package org.geeksforgeeks.drawlines
  
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
  
class MainActivity : AppCompatActivity(), View.OnTouchListener {
  
    // Declaring ImageView, Bitmap, Canvas, Paint,
    // Down Coordinates and Up Coordinates
    private lateinit var mImageView: ImageView
    private lateinit var bitmap: Bitmap
    private lateinit var canvas: Canvas
    private lateinit var paint: Paint
    private var downX = 0f
    private var downY = 0f
    private var upX = 0f
    private var upY = 0f
  
    @RequiresApi(Build.VERSION_CODES.R)
    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Initializing the ImageView
        mImageView = findViewById(R.id.image_view_1)
  
        // Getting the current window dimensions
        val currentDisplay = windowManager.currentWindowMetrics
        val dw = currentDisplay.bounds.width()
        val dh = currentDisplay.bounds.height()
  
        // Creating a bitmap with fetched dimensions
        bitmap = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888)
          
        // Storing the canvas on the bitmap
        canvas = Canvas(bitmap)
          
        // Initializing Paint to determine 
        // stoke attributes like color and size
        paint = Paint()
        paint.color = Color.RED
        paint.strokeWidth = 10F
        
        // Setting the bitmap on ImageView
        mImageView.setImageBitmap(bitmap)
          
        // Setting onTouchListener on the ImageView
        mImageView.setOnTouchListener(this)
    }
  
    // When Touch is detected on the ImageView, 
    // Initial and final coordinates are recorded
    // and a line is drawn between them.
    // ImagView is updated
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                downX = event.x
                downY = event.y
            }
  
            MotionEvent.ACTION_UP -> {
                upX = event.x
                upY = event.y
                canvas.drawLine(downX, downY, upX, upY, paint)
                mImageView.invalidate()
            }
        }
        return true
    }
}


第 3 步:使用 MainActivity.kt 文件

转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。

科特林

package org.geeksforgeeks.drawlines
  
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
  
class MainActivity : AppCompatActivity(), View.OnTouchListener {
  
    // Declaring ImageView, Bitmap, Canvas, Paint,
    // Down Coordinates and Up Coordinates
    private lateinit var mImageView: ImageView
    private lateinit var bitmap: Bitmap
    private lateinit var canvas: Canvas
    private lateinit var paint: Paint
    private var downX = 0f
    private var downY = 0f
    private var upX = 0f
    private var upY = 0f
  
    @RequiresApi(Build.VERSION_CODES.R)
    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Initializing the ImageView
        mImageView = findViewById(R.id.image_view_1)
  
        // Getting the current window dimensions
        val currentDisplay = windowManager.currentWindowMetrics
        val dw = currentDisplay.bounds.width()
        val dh = currentDisplay.bounds.height()
  
        // Creating a bitmap with fetched dimensions
        bitmap = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888)
          
        // Storing the canvas on the bitmap
        canvas = Canvas(bitmap)
          
        // Initializing Paint to determine 
        // stoke attributes like color and size
        paint = Paint()
        paint.color = Color.RED
        paint.strokeWidth = 10F
        
        // Setting the bitmap on ImageView
        mImageView.setImageBitmap(bitmap)
          
        // Setting onTouchListener on the ImageView
        mImageView.setOnTouchListener(this)
    }
  
    // When Touch is detected on the ImageView, 
    // Initial and final coordinates are recorded
    // and a line is drawn between them.
    // ImagView is updated
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                downX = event.x
                downY = event.y
            }
  
            MotionEvent.ACTION_UP -> {
                upX = event.x
                upY = event.y
                canvas.drawLine(downX, downY, upX, upY, paint)
                mImageView.invalidate()
            }
        }
        return true
    }
}

输出:

你可以看到我们可以在屏幕上画线。