怎么在Android中利用Canvas对象实现一个刮刮乐效果

这篇文章将为大家详细讲解有关怎么在Android中利用Canvas对象实现一个刮刮乐效果,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

布局文件

<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/after" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/a" /> 
 
  <ImageView 
    android:id="@+id/before" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/b" /> 
 
</FrameLayout>

Activity代码

public class MainActivity extends Activity implements OnTouchListener { 
 
  private ImageView imgafter; 
  private ImageView imgbefore; 
  private Canvas canvas; 
  private Paint paint; 
  private Bitmap bitmap; 
  private Bitmap before; 
  private Bitmap after; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
 
    imgafter = (ImageView) findViewById(R.id.after); 
    imgbefore = (ImageView) findViewById(R.id.before); 
 
    // 获得图片 
    after = BitmapFactory.decodeResource(getResources(), R.drawable.a); 
    before = BitmapFactory.decodeResource(getResources(), R.drawable.b); 
 
    imgafter.setImageBitmap(after); 
    imgbefore.setImageBitmap(before); 
    // 创建可以修改的空白的bitmap 
    bitmap = Bitmap.createBitmap(before.getWidth(), before.getHeight(), 
        before.getConfig()); 
    imgbefore.setOnTouchListener(this); 
    paint = new Paint(); 
    paint.setStrokeWidth(5); 
    paint.setColor(Color.BLACK); 
    // 创建画布 
    canvas = new Canvas(bitmap); 
    canvas.drawBitmap(before, new Matrix(), paint); 
  } 
 
  @Override 
  public boolean onTouch(View arg0, MotionEvent event) { 
    switch (event.getAction()) { 
    case MotionEvent.ACTION_MOVE: 
      int newX = (int) event.getX(); 
      int newY = (int) event.getY(); 
      // 将滑过的地方变为透明 
      for (int i = -10; i < 10; i++) { 
        for (int j = -10; j < 10; j++) { 
          if ((i + newX) >= before.getWidth() 
              || j + newY >= before.getHeight() || i + newX < 0 
              || j + newY < 0) { 
            return false; 
          } 
          bitmap.setPixel(i + newX, j + newY, Color.TRANSPARENT); 
        } 
      } 
      imgbefore.setImageBitmap(bitmap); 
      break; 
    } 
    return true; 
  } 
}

关于怎么在Android中利用Canvas对象实现一个刮刮乐效果就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。