activity_main.xml文件
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:id="@+id/layout"
tools:context="com.example.lenovo.androidstudy.MainActivity">
</FrameLayout>
MainAcivity.java文件`
package com.example;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout layout=(FrameLayout)findViewById(R.id.layout);//获得帧布局
final starView star=new starView(this);//创建一个自定义的starView的View对象
star.setOnTouchListener(new View.OnTouchListener() {//给view对象创建一个触摸的监听事件
@Override
public boolean onTouch(View v, MotionEvent event) {
star.setBitmapX(event.getX());//设置view的坐标为手指触碰的坐标
star.setBitmapY(event.getY());
star.invalidate();//使原来的整个窗口无效,对view进行刷新重绘
return true;
}
});
layout.addView(star);//向布局中添加组件
}
}
starView.java文件
package com.example;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
/**
* Created by Lenovo on 2020-05-12.
*/
public class starView extends View{
private float bitmapX;//设置view的X坐标
private float bitmapY;//设置view的Y坐标
//自定义View需要实现一个显示的构造方法,并且重写onDraw方法,一切操作都将在这个方法上执行
public starView(Context context)
{
super(context);
bitmapX=200;//设置view的初始位置
bitmapY=100;
}
//getters and setters
public float getBitmapX() {
return bitmapX;
}
public void setBitmapX(float bitmapX) {
this.bitmapX = bitmapX;
}
public float getBitmapY() {
return bitmapY;
}
public void setBitmapY(float bitmapY) {
this.bitmapY = bitmapY;
}
public void onDraw(Canvas canvas) {//重写draw方法
super.onDraw(canvas);
Paint paint=new Paint();//画笔
Bitmap bitmap= BitmapFactory.decodeResource(this.getResources(),R.drawable.mickey);
canvas.drawBitmap(bitmap,bitmapX,bitmapY,paint);//canvas画布绘制图片
if(bitmap.isRecycled())
bitmap.recycle();
}
}