刮刮卡效果的原理
paint.setXferMode();
先绘制一个图像层1,用户再手绘的部分为2。交际的部分就是要显示的部分。
先来点基础的
之前有做过一个类似画板的demo
public class MyviewDraw extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.ontouchdraw);
}
}
主布局文件
<LinearLayout 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:orientation="vertical"
tools:context="com.example.demotest.MainActivity" >
<!-- 导入自定义的空间 -->
<com.example.demotest2.MypiantView
android:id="@+id/myview"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</com.example.demotest2.MypiantView>
</LinearLayout>
主要看重写的MypiantView
package com.example.demotest2;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class MypiantView extends View {
private List<Point> allpoints = new ArrayList<Point>();;
// 用容器来保存所有坐标
public MypiantView(Context context, AttributeSet attrs) {
super(context, attrs);
super.setBackgroundColor(Color.WHITE);
super.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Point point = new Point((int) event.getX(), (int) event.getY());
if (event.getAction() == MotionEvent.ACTION_DOWN) {
allpoints = new ArrayList<Point>();// 初始化
allpoints.add(point);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
allpoints.add(point);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
allpoints.add(point);
MypiantView.this.postInvalidate();// 重新绘制
}
return true;// 表示不再执行了
}
});
}
// 重写andraw方法
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.RED);
if (allpoints.size() > 1) {
// 用集合来装点,遍历每个点
Iterator<Point> iterator = allpoints.iterator();
Point firstPoint = null;// 开始点
Point lastpPoint = null;// 结束点
while (iterator.hasNext()) {
if (firstPoint == null) {// 找到开始点
firstPoint = (Point) iterator.next();
} else {
if (lastpPoint != null) {
firstPoint = lastpPoint;
}
lastpPoint = (Point) iterator.next();
canvas.drawLine(firstPoint.x, firstPoint.y, lastpPoint.x, lastpPoint.y, paint);// 画线
}
}
}
super.onDraw(canvas);
}
}
效果如下
这只是实现了普通的画布 刮刮卡还是没有看懂,以后看懂了再来补充 挖坑+1~~~