運行結果展示:
小兔子的圖片會根據鼠標的位置而移動
需瞭解的知識
View 中有以下一些常用的方法:
- onFinishInflate() – 從 XML 加載組件後的回調
- onSizeChanged() – 組件大小發生變化時的回調
- onMeasure() – 回調此方法對組件大小進行測量
- onLayout() – 回調該方法來確定顯示的位置
- onTouchEvent() – 監聽到觸摸事件時的回調
Canvas
控件的所有繪製工作最終都會交由canvas來處理,Canvas被draw調用,當draw的時候需要4個基本的元素:
- a Bitmap to hold the pixels (一個bitmap來存放所有的像素)
- a Canvas to host the draw calls (writing into the bitmap)(canvas來主持draw的調用,將像素寫入bitmap)
- a drawing primitive (e.g. Rect, Path, text, Bitmap), (繪製的具體內容,可以文本,圖片,形狀之類)
- a paint (to describe the colors and styles for the drawing).(一隻‘筆’,用來定義顏色,和繪製的類型)
鼠標監聽
幀佈局
代碼如下:
重寫的onDraw()函數:一個bitmap,具體位置,一支畫筆
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint=new Paint();
Bitmap bitmap= BitmapFactory.decodeResource(this.getResources(),R.mipmap.rabbit);
canvas.drawBitmap(bitmap,bitmapX,bitmapY,paint);
if(bitmap.isRecycled()){
bitmap.recycle();
}
}
幀佈局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/back"
android:id="@+id/my1"
>
</FrameLayout>
重寫的onCreat()函數:創建對象,鼠標監聽其位置
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame);
FrameLayout frameLayout=(FrameLayout) findViewById(R.id.my1);
final RabbitView rabbit=new RabbitView(this);
rabbit.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
rabbit.bitmapX=event.getX();
rabbit.bitmapY=event.getY();
rabbit.invalidate();
return true;
}
});
frameLayout.addView(rabbit);
}