實現思路
說說實現的大概思路,首先要有兩副圖片。這兩幅圖片的區別就在於一副有穿衣服,另外一副沒有穿衣服,其他的細節都要一模一樣。這對於懂ps的童鞋就好辦啦自己動手製作就好了。但是本文爲了照顧不懂ps的童鞋,提供兩幅圖片供大家使用~~圖中美女不美各位不要吐槽哈~。
A圖:沒穿衣服(after1)
B圖:有衣服的(pre1)
首先一開始是把A圖放在屏幕上,然後再把B圖覆蓋在A圖上。那樣用戶一開始看到的是B圖。我們通過,監聽手指移動到哪些座標上,就設置這些座標的顏色爲透明色。那麼用戶看到的就是A圖,也就達到了扒衣服的效果。
大概思路簡單敘述完了,那麼接下來看看詳細代碼:
具體實現
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<ImageView
android:src="@drawable/after1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/iv2
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.pre1);
在對B圖進行處理之前我們先得出B圖的副本copyBitmap:
copyBitmap=Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
Canvas canvas=new Canvas(copyBitmap);
3.new一支畫筆出來,並設置默認顏色: Paint paint=new Paint();
paint.setColor(Color.BLACK);
4.最後照着B圖“畫”出來
canvas.drawBitmap(bitmap, new Matrix(), paint);
就這樣copyBitmap就與B圖的實例bitmap一模一樣了,也就是說已經創建出B圖的的副本啦。 iv2.setImageBitmap(bitmap);
現在運行會看到是這個樣子的:
iv2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX();
int y = (int) event.getY();
copyBitmap.setPixel(x, y , Color.TRANSPARENT);
iv2.setImageBitmap(copyBitmap);
Log.i("test", x + "," + y);
break;
}
return true;
}
});
copyBitmap.setPixel(x, y , Color.TRANSPARENT);代碼就是將座標爲想x,y的像素點設置爲透明色,而event.getX()與event.getY()則是分別獲取用戶觸摸控件上的x座標和y座標。請注意這裏筆者說的是控件上的座標,並不是屏幕上的座標。關於屏幕座標與控件座標的區別可以看以下博文
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX();
int y = (int) event.getY();
for (int i = -18; i < 20; i++) {
for (int j = -18; j < 20; j++) {
try {
copyBitmap.setPixel(x + i, y + j, Color.TRANSPARENT);
} catch (Exception e) {
// TODO: handle exception
}
}
}
iv2.setImageBitmap(copyBitmap);
Log.i("test", x + "," + y);
break;
iv2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.higirl);
mediaPlayer.start();;
break;
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX();
int y = (int) event.getY();
for (int i = -18; i < 20; i++) {
for (int j = -18; j < 20; j++) {
try {
copyBitmap.setPixel(x + i, y + j, Color.TRANSPARENT);
} catch (Exception e) {
// TODO: handle exception
}
}
}
iv2.setImageBitmap(copyBitmap);
Log.i("test", x + "," + y);
break;
case MotionEvent.ACTION_DOWN:
if(mediaPlayer!=null){
mediaPlayer.stop();
mediaPlayer.release();
}
break;
}
return true;
}
聲音文件筆者放到res\raw裏面了。