实现效果
主要代码
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/img_info" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/b" /> <ImageView android:id="@+id/img_surface" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/a" /> </FrameLayout>
注意:图片位置不要设置,表面图片要大于底层图片
MainActivity.java
package com.example.guaguale; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; /** * 刮刮乐 * * @author zhaoyazhi * * 2014-6-18 */ public class MainActivity extends Activity implements OnTouchListener { private Canvas canvas; private Paint paint; private Bitmap bitmap; private ImageView imgInfo; private ImageView imgSurface; private Bitmap bSurface;// 没有刮开的表面图片 private Bitmap bInfo;// 刮开后的显示内容 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imgSurface = (ImageView) findViewById(R.id.img_surface); imgInfo = (ImageView) findViewById(R.id.img_info); // 获得图片 // 参数1:res是资源的引用,参数2:id是图片的id bSurface = BitmapFactory.decodeResource(getResources(), R.drawable.a); bInfo = BitmapFactory.decodeResource(getResources(), R.drawable.b); // 设置图片 imgSurface.setImageBitmap(bSurface); imgInfo.setImageBitmap(bInfo); // 创建可以修改的空白的bitmap bitmap = Bitmap.createBitmap(bSurface.getWidth(), bSurface.getHeight(), bSurface.getConfig()); // 设置屏幕触摸事件 imgSurface.setOnTouchListener(this); // 创建画笔 paint = new Paint(); // 创建画布 canvas = new Canvas(bitmap); canvas.drawBitmap(bSurface, new Matrix(), paint); } /** * 用户触摸屏幕时候的事件 */ @Override public boolean onTouch(View view, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_MOVE: int newX = (int) event.getX(); int newY = (int) event.getY(); // i ,j每一个透明单位的大小 for (int i = -10; i < 10; i++) { for (int j = -10; j < 10; j++) { //图片之外的区域 if ((i + newX) >= bSurface.getWidth() || j + newY >= bSurface.getHeight() || i + newX < 0 || j + newY < 0) { return false; } //将滑过的地方变为透明 bitmap.setPixel(i + newX, j + newY, Color.TRANSPARENT); } } //设置透明区域 imgSurface.setImageBitmap(bitmap); break; } return true; } }
涉及知识点
getResources()
http://blog.csdn.net/zhaoyazhi2129/article/details/32077513
setImageBitmap
http://blog.csdn.net/zhaoyazhi2129/article/details/32080827
paint画笔
http://blog.csdn.net/zhaoyazhi2129/article/details/32090187
canvas画布
http://blog.csdn.net/zhaoyazhi2129/article/details/32098477
bitmap
http://blog.csdn.net/zhaoyazhi2129/article/details/32136179