更换衣服游戏的原理:原本有2个图片,一个原图片,一个更被换了衣服以后的图片。两个图片放在一起,原图片放在上面,收滑动的时候上面图片的像素点设置成透明,下面的图片像素点显示出来了。
布局文件
activity_main.xml
<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/xiatu" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shangtu" />
</RelativeLayout>
MainActivity.java
package com.ldw.siyifu;
import android.R.color;
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;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取到原图片
Bitmap bitSrc = BitmapFactory.decodeResource(getResources(), R.drawable.awaiyi);
//创建外衣副本
final Bitmap bitCopy = Bitmap.createBitmap(bitSrc.getWidth(), bitSrc.getHeight(), bitSrc.getConfig());
Paint paint = new Paint();
Canvas canvas = new Canvas(bitCopy);
canvas.drawBitmap(bitSrc, new Matrix(), paint);
final ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bitCopy);
iv.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch(action){
//触摸屏幕
case MotionEvent.ACTION_DOWN:
break;
//屏幕上移动
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX();
int y = (int) event.getY();
//限制编辑的区域,在图片的区域内才允许编辑
if(x <= bitCopy.getWidth() && y<= bitCopy.getHeight()){
//隐藏不止一个像素点,把周围的像素点都隐藏
for(int i = -5; i <= 5; i++){
for(int j = -5; j <= 5; j++){
//涂抹的像素点是一个圆形
if( i*i + j*j <= 25){
//防止越界,上下左右设置边界
if( x + i < bitCopy.getWidth() && y + j < bitCopy.getHeight() && x + i > 0 && y + j > 0){
//用户滑动过的坐标设置成透明
bitCopy.setPixel(x + i , y + j, Color.TRANSPARENT);
iv.setImageBitmap(bitCopy);
}
}
}
}
}
break;
//离开屏幕
case MotionEvent.ACTION_UP:
break;
}
//true:告诉系统,这个事件由自己处理,
//false:告诉系统,事件由自己处理,系统会把触摸事件发送到iamgeView的父节点
return true;
}
});
}
}