LoginSignup
1
1

More than 5 years have passed since last update.

画像の任意の領域のクリック判定のやり方

Posted at

やろうとしていること

画像をクリックして、特定の範囲だったらアイテムを取得するように判定したい。
下記のサイトを参考に、実装してみた。

つまった部分

tryとcatch

tryとはjavaにおいて例外を処理する基本の操作方法である。


try{
例外をスローする可能性のある処理
}
catch(例外クラス型 引数名){
例外処理(例外ハンドラ)
} 
finally {
  最後に必ず実行される処理  //fainallyは無くても実行できる
}

今回try内で実行しているのはInputstreamでファイルを開き、mBitmapに渡している。assetsフォルダ(下記で説明)の中に指定したファイルが無い時などにcatch内のコードが実行される。
参考にしていたコードでは例外が発生したときに何も実行しないようになっていたが、e.printStackTrace()を実行することで標準出力に原因が出力される。

try {
   InputStream is = getResources().getAssets().open("sirokuma.jpg");
   mBitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {
   e.printStackTrace();
}

InputStream is = getResources().getAssets().open("sirokuma.jpg");でしていること

Inputstreamとは

バイナリファイルを読み込むクラス。isは頭文字をとって命名されている。

Assetsフォルダー

\AndroidStudioProjects\Test_Application(アプリ名)\app\src\mainの中に置かれているフォルダー。複数の画像ファイルなどをまとめておいておける。res/drawableと何が違うかよくわからない。

スクリーンショット (20)_LI.jpg
ここにいれておけばgetResources().getAssets().open("ファイル名")で開くことが出来る。
複数のファイルを読み込むなど、何度も記述する場合はgetResources().getAssets()の部分をAssetManagerとしてまとめると可読性が高まる。
AssetManager assetManager = getResources().getAssets();
assetManager.open("ファイル1");
assetManager.open("ファイル2");

Assetsフォルダーの作り方

mainファイルを選択し右クリック/New/Folder/Assets Folderとすると作成してくれる。
スクリーンショット (21)_LI.jpg

参考にしたサイト
http://pentan.info/android/app/sample/asset_manager.html

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1