1.准备两张一样的图片,一张是穿有衣服的,另一张是没有穿衣服的。
2.通过FrameLayout进行布局,穿衣服的放上面,没穿衣服的图片放下面。
3.通过触摸事件进行判断,手指划过的地方,让穿衣服的图片变成透明,就显示到了下面没穿衣服的图片。
这样效果就形成了。先让大家看一下效果图:
撕衣服之前:
撕衣服之后:
下面请看代码吧。
首先是MainActivity里的代码:
package net.loonggg.tornclothes; 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.widget.ImageView; public class MainActivity extends Activity { private static final int RADIUS = 10; private ImageView afterIv, beforeIv; private Canvas canvas; private Paint paint; private Bitmap beforeBitmap; private Bitmap afterBitmap; private Bitmap updateBitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); afterIv = (ImageView) findViewById(R.id.iv_after); beforeIv = (ImageView) findViewById(R.id.iv_before); // 通过这种方法读取的bitmap是只读的,不可修改 beforeBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.g6_up); afterBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.g6_back); // 因为上边获得的图片是只读的,所以重新创建一个一模一样的图片,来操作这个图片 updateBitmap = Bitmap.createBitmap(beforeBitmap.getWidth(), beforeBitmap.getHeight(), beforeBitmap.getConfig()); canvas = new Canvas(updateBitmap); paint = new Paint(); paint.setStrokeWidth(5); paint.setColor(Color.BLACK); canvas.drawBitmap(beforeBitmap, new Matrix(), paint); afterIv.setImageBitmap(afterBitmap); beforeIv.setImageBitmap(updateBitmap); beforeIv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_MOVE: int touchX = (int) event.getX(); int touchY = (int) event.getY(); // 这个判断是计算边界,因为超过了边界为负值时会报错 if (touchX >= RADIUS & touchX <= beforeIv.getWidth() - RADIUS & touchY >= RADIUS & touchY <= beforeIv.getHeight() - RADIUS) { /** * 计算圆,挖空一个半径为RADIUS的实心圆 */ for (int radius = 0; radius <= RADIUS; radius++) { for (double angle = 0; angle <= 360; angle++) { double newX = touchX + radius * Math.cos(angle); double newY = touchY + radius * Math.sin(angle); updateBitmap.setPixel((int) newX, (int) newY, Color.TRANSPARENT); } } beforeIv.setImageBitmap(updateBitmap); } break; default: break; } return true; } }); } }然后就是布局文件的代码:
<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/iv_after" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/iv_before" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout>到这里就完了,非常简单吧!哈哈……学会了吧!
转载请注明出处:http://blog.csdn.net/loongggdroid/article/details/18601555