画像の任意の領域のクリック判定
これは、Viewの拡大、縮小などに使われる
画像の任意の領域のタッチ判定するには
Viewクラスを拡張する
class MyView extends View{
というように、extends View で継承する
次に、画像の読み込みに
Bitmap
PaintクラスとPathクラスで短形の描画
Regionクラスであたり判定
というように、使う
private Bitmap mBitmap; private Path mPath = new Path(); private Paint mPaint = new Paint(); private Region mRegion = new Region();
で、メンバ変数と初期化宣言
そして、画像の読み込みと枠の設定
読み込みでは、例外発生に備え
try catchで行う
public MyView(Context context){
super(context);
//画像の取得
try{
InputStream is = getResources().getAssets().open("test.jpg");
mBitmap = BitmapFactory.decodeStream(is);
}catch(Exception e){
}
//クリックしたときの赤い枠の設定
//色の指定
mPaint.setColor(Color.RED);
//枠の幅
mPaint.setStrokeWidth(3);
//枠の描画方法
mPaint.setStyle(Style.STROKE);
//枠の大きさ設定
Rect rect = new Rect(100, 100, 300, 300);
mPath.addRect(new RectF(rect), Path.Direction.CW);
mRegion.set(rect);
}
そして、描画処理
protected void onDraw(Canvas canvas){
canvas.save();
canvas.drawBitmap(mBitmap,0,0,null);
canvas.drawPath(mPath, mPaint);
canvas.restore();
}
そして、タッチイベントの実装
今回は、トーストを表示する
@Override
public void onTouchEvent(MotionEvent e){
if(e.getAction() == MotionEvent.ACTION_UP){
if(mRegion.contains((int) e.getX(), e.getY())){
Toast.makeText(getContext(), "タッチしたよ",Toast.LENGTH_SHORT).show();
}
}
return false;
}
onTouchEvent()では、
Regionクラスの
contains()を使うことであたり判定をしてる
そして、タッチした座標が
e.getX()
e.getY()
で取得できてるので
領域内ならトーストを表示するようにしている