Android自定义橡皮擦效果-创新互联

本文实例为大家分享了Android自定义橡皮擦效果,使用贝塞尔曲线处理曲线转折处

目前创新互联已为成百上千家的企业提供了网站建设、域名、网站空间绵阳服务器托管、企业网站设计、松山网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
public class picFingerToTest extends View {

  private Paint paint;
  private Bitmap decodeResourceSRC;
  private Bitmap createBitmapDST;
  // 手指路径,使用贝塞尔路线
  private Path path;
  private float perX;
  private float perY;

  public picFingerToTest(Context context, AttributeSet attrs) {
    super(context, attrs);
    // 1、设置禁用硬件设置
    setLayerType(View.LAYER_TYPE_SOFTWARE, null);

    // 2、设置手指画笔
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(45);

    // 3、生成图像手指源目标
    // 源
    decodeResourceSRC = BitmapFactory.decodeResource(getResources(), R.drawable.welcome, null);
    // 目标
    createBitmapDST = Bitmap.createBitmap(decodeResourceSRC.getWidth(), decodeResourceSRC.getHeight(),
        Config.ARGB_8888);
    path = new Path();

  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 分层绘制
    int saveLayer = canvas.saveLayer(0, 0, getWidth(), getHeight(), null,Canvas.ALL_SAVE_FLAG);

    // 把手指轨迹划到目标路径上
    Canvas canvas2 = new Canvas(createBitmapDST);
    canvas2.drawPath(path, paint);

    // 把目标图像画到画布上
    canvas.drawBitmap(createBitmapDST, 0, 0, paint);

    // 计算源图像区域

    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
    canvas.drawBitmap(decodeResourceSRC, 0, 0, paint);

    paint.setXfermode(null);
    canvas.restoreToCount(saveLayer);

  }

  //使用贝塞尔曲线,使折线过度圆滑
  @Override
  public boolean onTouchEvent(MotionEvent event) {

    switch (event.getAction()) {
    // 记录手指触摸的初始化位置
    case MotionEvent.ACTION_DOWN:

      path.moveTo(event.getX(), event.getY());

      perX = event.getX();
      perY = event.getY();

      return true;

    case MotionEvent.ACTION_MOVE:

      float endX = (perX + event.getX()) / 2;
      float endY = (perY + event.getY()) / 2;

      path.quadTo(perX, perY, endX, endY);
      perX = event.getX();
      perY = event.getY();
      postInvalidate();

      break;
    case MotionEvent.ACTION_UP:

      break;

    default:
      break;
    }

    return super.onTouchEvent(event);
  }

}


名称栏目:Android自定义橡皮擦效果-创新互联
文章分享:http://scyanting.com/article/ddcpgj.html