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

【Android】PicassoライブラリでURLからImageViewに画像を読み込む方法

Androidアプリ開発では、ネットワーク上の画像をImageViewに表示したい場面がよくあります。本記事では、Square社が提供する画像読み込みライブラリ「Picasso」を使用して、URLから画像を取得しImageViewに表示する方法を、手順を追ってわかりやすく解説します。

Picassoとは?

Picassoは、Android向けの定番画像ライブラリです。URLを指定するだけで、画像のダウンロード・キャッシュ管理・メモリ効率の最適化を自動的に行ってくれるため、わずか1行のコードで画像を表示できます。

実装手順

ステップ1:新規プロジェクトを作成する

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

ステップ2:Gradleに依存関係を追加する

「Gradle Scripts」→「build.gradle (Module: app)」を開き、dependenciesブロックに以下の依存関係を追加します。その後、画面上部に表示される「Sync now」をクリックして同期を行いましょう。

implementation 'com.squareup.picasso:picasso:2.5.2'

ステップ3:レイアウトファイルを編集する

res/layout/activity_main.xml に以下のコードを記述します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load ImageView by URL"
        android:textStyle="bold"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp" />
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="fill_parent"
        android:layout_height="300dp"
        android:layout_marginTop="16dp" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:textSize="24sp"
        android:gravity="center|bottom"
        android:textStyle="bold" />
</LinearLayout>

ステップ4:MainActivity.java を編集する

src/MainActivity.java に以下のコードを記述します。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = findViewById(R.id.image_view);
        String url = "https://images.pexels.com/photos/814499/pexels-photo814499.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
        Picasso.with(this).load(url).into(imageView);
    }
}

重要なのは次の1行だけです。

Picasso.with(this).load(url).into(imageView);

この1行で、指定したURLから画像がバックグラウンドで非同期に読み込まれ、ImageViewに自動的にセットされます。スレッド管理やエラー処理を自分で書く必要がないのがPicassoの大きな魅力です。

ステップ5: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">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        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スマートフォンをPCに接続していることを前提とします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。接続したモバイルデバイスを選択すると、端末の画面にURLから読み込まれた画像が表示されます。

【Android】PicassoライブラリでURLからImageViewに画像を読み込む方法

補足:新しいバージョンのPicassoを使う場合

Picasso 2.71828 以降では Picasso.with() は非推奨となり、代わりに Picasso.get() を使用します。最新版を利用する場合は、以下のように書き換えてください。

Picasso.get().load(url).into(imageView);

  1. AndroidでImageViewの画像を指定した角度で回転させる方法

    このチュートリアルでは、AndroidアプリでImageViewに表示した画像を、指定した角度で回転させる方法を解説します。サンプルとして、ボタンをタップすると画像が90度回転するシンプルなアプリを作成します。 ステップ1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 ステップ2:レイアウトファイル(activity_main.xml)にコードを追加する res/layout/activity_main.xml に以下のコードを記述します。

  2. Android Picassoライブラリで画像をダウンロード・表示する方法を徹底解説

    Picassoは、Square社が提供するAndroid向けの定番画像読み込みライブラリです。URLを指定するだけで、画像のダウンロードからキャッシュ管理、画面への表示まで自動的に処理してくれるため、ネットワーク通信のコードを自前で書く必要がありません。本記事では、Picassoを使って画像をダウンロードし、ImageViewに表示する方法をステップごとに解説します。 ステップ1:プロジェクトの作成と依存関係の追加 まず、Android Studioで新しいプロジェクトを作成します。メニューバーから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してくだ