写在前面
很快就进入了安卓学习阶段,安卓学习阶段再也不会有终端的输出而看着恼火,安卓阶段会用界面来真机演示,这个过程再也不会枯燥了。
还要强调一点,就是下面这个小项目完全绿色,无毒无害。
思路与准备
前面一节已经大体上介绍了Android工程的目录,以及每个目录的作用,下面我们就来实现我们这个小项目吧。
思路:
--对于这个项目,其主要功能就是当我们手指在屏幕划过时,会将上面一成图片给去掉,显示下面一层图片;
--创建两张图片,创建触摸事件,当是手指划过时,将划过点的坐标对应的像素换成透明的颜色,这样子就会把底层的图片显示出来。
扩展:
这个项目的思路也可以用来做刮奖,具体实现,以后有时间我会更新在博客中。
代码实现
java代码
/**
* 撕衣服的思路:使用透明色替换原有图片的对应点的像素,立刻获取替换之后的图片,并且显示在ImageView上
*/
public class MainActivity extends AppCompatActivity {
ImageView forground;
Bitmap copyBitmap;
Canvas canvas;
Paint paint;
@Override //创建一个界面,界面如何布局
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//配置界面
setContentView(R.layout.activity_main);
//找到容器里面对应的图片控件 findViewById
forground = findViewById(R.id.iv_forground);
//将需要操作的图片读取出来 Bitmap
// BitmapFactory用于管理位图
// decodeResource从工程的资源路径中去生成一张位图
// getResources()获取工程资源
// R.drawable.fr获取资源路径下drawable里面的一张fr的tp
Bitmap orgBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.fr);
//替换操作这张图片 用透明色去替换某个位置的颜色
//不能操作原图 只能拷贝一份
//创建一个和原始图片相同环境的空位图
copyBitmap = Bitmap.createBitmap(orgBitmap.getWidth(),orgBitmap.getHeight(),orgBitmap.getConfig());
//orgBitmap.setPixel(240,400,Color.WHITE);
//创建一个canvas 画布 现实中的话板
canvas =new Canvas(copyBitmap);
//创建一个画笔
paint = new Paint();
//创建一个矩阵
Matrix matrix = new Matrix();
//旋转图片
//matrix.setRotate(90,240,400);
//平移
//matrix.setTranslate(50,0);
//翻转
//matrix.setScale(-1f,1f);
//matrix.postTranslate(orgBitmap.getWidth(),0);
//画一副画
canvas.drawBitmap(orgBitmap,matrix,paint);
//显示图片
forground.setImageBitmap(copyBitmap);
//给前景图片添加touch手势
//当有触摸事件发生,系统就会接收并回调这个事件
forground.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//获取当前事件
int action = event.getAction();
//判断状态
if(action == MotionEvent.ACTION_MOVE){
//获取触摸点的坐标
int x = (int)event.getX();
int y = (int)event.getY();
//替换xy对应的像素
for (int i = -8; i<8; i++){
for (int j = -8; j<8; j++){
copyBitmap.setPixel(x+i,y+j,Color.TRANSPARENT);
}
}
//canvas.drawBitmap(orgBitmap, new Matrix(),paint);
//显示图片
forground.setImageBitmap(copyBitmap);
}
return true;
}
});
}
xml代码
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.a18168.tearcloth.MainActivity"
android:id="@+id/fl_main">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/bg" />
<ImageView
android:id="@+id/iv_forground"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
网友评论