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

AndroidでImageViewの幅と高さを取得する方法【サンプルコード付き】

この記事では、Androidアプリ開発において android.widget.ImageView の幅(width)と高さ(height)を取得する方法を、実際に動作するサンプルコードとともにステップごとに解説します。

実装の全体像

ImageViewのサイズを取得するには、getWidth() メソッドと getHeight() メソッドを使用します。ここでは、ボタンをタップしたときにImageViewのサイズを取得し、TextViewに結果を表示するシンプルなサンプルアプリを作成します。

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

Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目を入力して、新しいプロジェクトの作成を完了させてください。

手順2:レイアウトファイルを編集する

res/layout/activity_main.xml に以下のコードを追加します。画面にはImageView、サイズ確認用のButton、結果表示用のTextViewを縦方向に配置しています。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_marginTop="30dp"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:src="@drawable/image"/>
    <Button
        android:id="@+id/btnCheckSize"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp"
        android:textSize="12sp"
        android:textStyle="bold"
        android:text="Check ImageView size"/>
    <TextView
        android:id="@+id/textView"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="16sp"
        android:textStyle="bold"/>
</LinearLayout>

手順3:MainActivity.java を実装する

src/MainActivity.java に以下のコードを追加します。ボタンがクリックされたタイミングで getWidth()getHeight() を呼び出し、取得した値をTextViewに表示します。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button button;
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.btnCheckSize);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText(String.format("Size of ImageView:\nHeight: %s\nWidth: %s", String.valueOf(imageView.getWidth()), String.valueOf(imageView.getHeight())));
            }
        });
    }
}

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

androidManifest.xml に以下のコードを追加します(通常はプロジェクト作成時に自動生成されています)。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <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」アイコンをクリックします。実行デバイスとして自分のモバイル端末を選択すると、端末に以下の初期画面が表示されます。

AndroidでImageViewの幅と高さを取得する方法【サンプルコード付き】

AndroidでImageViewの幅と高さを取得する方法【サンプルコード付き】

解説:getWidth()とgetHeight()の注意点

getWidth()getHeight() は、ビューの実際のサイズをピクセル(px)単位で返します。重要なポイントとして、これらのメソッドはレイアウトが画面に描画される前(onCreate() 内で直接呼び出した場合など)には 0 を返します。そのため、このサンプルのようにボタンクリックのタイミングなど、ビューの描画が完了した後に呼び出すことが重要です。取得したpx値をdp単位に変換したい場合は、端末の画面密度(density)で割ることで変換できます。

  1. Tkinterでウィジェットの幅を取得する方法【winfo_width()の使い方】

    Tkinterウィジェットは、アプリケーションウィンドウ上に配置されるUI部品です。すべてのウィジェットは、あらかじめ用意されたプロパティや関数を使って自由に設定・カスタマイズできます。Tkinterアプリケーションでウィジェットの幅を取得するには、winfo_width()メソッドを使用します。このメソッドはウィジェットの実際の幅(ピクセル単位)を返し、その値を後から出力として表示できます。注意点winfo_width()は、ウィジェットが実際に画面へ描画された後の幅を返します。そのため、メソッドを呼び出す前にupdate()を実行してウィンドウを描画しておく必要があります。update()

  2. Tkinterでウィジェットの現在のX・Y座標を取得する方法

    Tkinterは、PythonでGUIアプリケーションを開発するために広く利用されている標準ライブラリです。ボタン、テキストボックス、ラベルなど、さまざまなウィジェットが用意されており、これらを組み合わせることで直感的なユーザーインターフェースを構築できます。さらに、ウィジェットの配置位置や座標も、専用の関数やライブラリを使って柔軟にカスタマイズすることが可能です。ここでは、Tkinterフレーム上に配置したウィジェットの実際の座標を取得する方法を紹介します。ウィジェットの正確な座標を知りたい場合には、Tkinterライブラリが提供するgeometry(ジオメトリ)関連のメソッドを活用します。