Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidアプリに線を描画する方法をステップごとに解説

KotlinでAndroidに線を描画する方法

このチュートリアルでは、Kotlinを使ってAndroidアプリに線を描画する方法を段階的に解説します。Bitmap・Canvas・Paintというグラフィックス関連のクラスを組み合わせることで、ボタンをタップしたときに画面へ線を表示できるようになります。

手順1:新規プロジェクトを作成する

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成しましょう。

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。描画した線を表示するための ImageView と、描画処理を実行する Button を配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="70dp"
        android:text="Draw Line" />
</RelativeLayout>

手順3:MainActivity.kt を編集する

次に、src/MainActivity.kt に以下のコードを追加します。

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var button: Button
    lateinit var imageView: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        button = findViewById(R.id.button)
        imageView = findViewById(R.id.imageView)
        button.setOnClickListener {
            val bitmap = Bitmap.createBitmap(10, 700, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            canvas.drawColor(Color.RED)
            val paint = Paint()
            paint.color = Color.RED
            paint.style = Paint.Style.STROKE
            paint.strokeWidth = 8F
            paint.isAntiAlias = true
            val offset = 50
            canvas.drawLine(
                offset.toFloat(),
                (canvas.height / 2).toFloat(),
                (canvas.width - offset).toFloat(),
                (canvas.height / 2).toFloat(),
                paint
            )
            imageView.setImageBitmap(bitmap)
        }
    }
}

このコードのポイントは以下の通りです。

  • Bitmap:描画結果を保持する画像データです。ここでは 10×700 ピクセルのビットマップを生成しています。
  • Canvas:ビットマップに対して図形を描き込むためのキャンバスです。
  • Paint:線の色・太さ・アンチエイリアスの有無など、描画スタイルを指定するクラスです。
  • drawLine():始点と終点の座標(X, Y)を指定して直線を描画します。

手順4:AndroidManifest.xml を確認する

AndroidManifest.xml は以下のようになります。このサンプルでは特別なパーミッションは不要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行して動作を確認する

それでは、アプリを実行してみましょう。実機のAndroid端末をパソコンに接続していることを前提としています。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。

KotlinでAndroidアプリに線を描画する方法をステップごとに解説

実行対象として接続済みのモバイルデバイスを選択すると、端末にアプリが起動します。ボタンをタップすると、赤い線が画面中央に描かれます。

KotlinでAndroidアプリに線を描画する方法をステップごとに解説

  1. C++とOpenCVを使って線を描画する方法

    OpenCVで線を描画するには、始点と終点の2つの座標が必要です。さらに、線を描くためのキャンバス(描画領域)も用意しなければなりません。線を描画するために必要な要素OpenCVでは、キャンバスとして機能するのが行列(Mat)です。この行列に対して、線の始点と終点を定義し、加えて以下の情報も指定します。線の色線の太さつまり、OpenCVで線を描くには、行列・2つの点・色・線の太さという4つの要素を宣言しておく必要があります。必要なヘッダーファイルOpenCVで線を描画するには、<imgproc.hpp>ヘッダーをインクルードします。これは、line()関数がこのヘッダー内で定義され

  2. JavaとOpenCVで線を描画する方法をわかりやすく解説

    Java版OpenCVライブラリのorg.opencv.imgprocパッケージには、Imgprocというクラスが含まれています。画像に直線を描画するには、このクラスが提供するline()メソッドを呼び出します。 line()メソッドのパラメータ line()メソッドは、以下のパラメータを受け取ります。 Matオブジェクト ― 直線を描画する対象となる画像を表します。 Pointオブジェクト2つ ― 直線の始点と終点の座標を表します。 Scalarオブジェクト ― 直線の色をBGR形式で指定します。 整数値 ― 直線の太さを指定します(デフォルト値:1)。 サンプルコード 以下は、白紙の画