案例代码:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
tools:context=".MainActivity">
</RelativeLayout>
AndroidView.java
package com.example.demo4;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
/**
* 创建自定义View,用来绘制安卓的logo
*/
public class AndroidView extends View {
public float bitmapX;
public float bitmapY;
public AndroidView(Context context) {
super(context);
bitmapX = 65;
bitmapY = 0;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
Bitmap bitmap = BitmapFactory.decodeResource(
this.getResources(),R.mipmap.ic_launcher);
canvas.drawBitmap(bitmap,bitmapX,bitmapY,paint);
if(bitmap.isRecycled()){
bitmap.recycle();
}
}
}
MainActivity.java
package com.example.demo4;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*第二步:创建并示例化帽子类的一个对象,并为AndroidLogo添加触摸
* 事件监听器,在重写的触摸方法中根据触摸的位置重新绘制
* Logo
*/
final AndroidView androidView = new AndroidView(MainActivity.this);
androidView.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
androidView.bitmapX = event.getX() - 80;
androidView.bitmapY = event.getY() - 80;
androidView.invalidate();
return true;
}
});
//第三步:把Logo添加到布局管理器中
RelativeLayout rl = (RelativeLayout)findViewById
(R.id.relativeLayout);
rl.addView(androidView);
}
}
原文:https://www.cnblogs.com/lzpq/p/12804369.html