實現效果以下android
注:編程
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公衆號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。 canvas
新建Android項目,首先打開activity_main.xmlapp
修改其爲FrameLayout幀佈局管理器,並添加Id屬性和背景照片ide
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg" tools:context=".MainActivity"> </FrameLayout>
而後在包下新建自定View類dog類佈局
使其繼承View類,而後聲明兩個float變量來存儲其位置。在其構造方法中對位置進行初始化。this
而後重寫onDraw方法,根據指定的位置進行重繪viewspa
package com.badao.defineview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; public class DogView extends View { public float bitmapX; public float bitmapY; public DogView(Context context) { super(context); bitmapX = 290; bitmapY = 130; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //新建畫筆對象 Paint paint = new Paint(); //獲取照片 Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.dog); //繪製照片 canvas.drawBitmap(bitmap,bitmapX,bitmapY,paint); //回收圖片 if(bitmap.isRecycled()) { bitmap.recycle(); } } }
而後回到MainActivity,獲取layout,聲明自定義的view並設置觸摸事件監聽器,將觸摸位置的座標賦值給自定義view的位置,而後重繪view,並將其添加到layout中.net
package com.badao.defineview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取layout FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frameLayout); //聲明自定義View final DogView dogView = new DogView(this); //設置觸摸事件監聽器 dogView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //獲取觸摸位置的X的座標 dogView.bitmapX = event.getX(); //獲取觸摸位置Y的座標 dogView.bitmapY = event.getY(); //須要重繪view dogView.invalidate(); return true; } }); //將自定義view添加到layout中 frameLayout.addView(dogView); } }