[原]安卓cavas.clipPath用法

重要的事情说三遍

cavas.clipPath不支持硬件加速,记得在AndroidManifest.xml中设置不使用硬件加速。不然效果出不来

cavas.clipPath不支持硬件加速,记得在AndroidManifest.xml中设置不使用硬件加速。不然效果出不来

cavas.clipPath不支持硬件加速,记得在AndroidManifest.xml中设置不使用硬件加速。不然效果出不来

<application android:label="@string/app_name" android:icon="@drawable/ic_launcher"
                 android:hardwareAccelerated="false">

 接下来看代码:

这是一个显示补集的例子。

注意两点:

Clip(剪切)的时机:通常理解的clip(剪切),是对已经存在的图形进行clip的。但是,在android上是对canvas(画布)上进行clip的,要在画图之前对canvas进行clip,如果画图之后再对canvas进行clip不会影响到已经画好的图形。一定要记住clip是针对canvas而非图形

Clip中的Op的参数的意思:

DIFFERENCE是第一次不同于第二次的部分显示出来A-B-------

REPLACE是显示第二次的B******

REVERSE_DIFFERENCE 是第二次不同于第一次的部分显示--------

INTERSECT交集显示A-(A-B)*******

UNION全部显示A+B******

XOR补集 就是全集的减去交集生育部分显示--------

package com.example.myapp.view;

import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by zyr on 15/9/8.
 */
public class MaskView extends View {
    private Paint paint;

    public MaskView(Context context) {
        super(context);
        init();
    }

    public MaskView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MaskView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void init(){
        paint = new Paint();
        paint.setColor(Color.RED);
//        paint.setStyle(Paint.Style.STROKE);//设置空心
        paint.setStrokeWidth(3);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //DIFFERENCE是第一次不同于第二次的部分显示出来A-B-------
        //REPLACE是显示第二次的B******
        //REVERSE_DIFFERENCE 是第二次不同于第一次的部分显示--------
        //INTERSECT交集显示A-(A-B)*******
        //UNION全部显示A+B******
        //XOR补集 就是全集的减去交集生育部分显示--------
        canvas.save();
        canvas.translate(10, 10);
        canvas.clipRect(0, 0, 300, 300);
        canvas.clipRect(200, 200, 400, 400, Region.Op.XOR);
        canvas.clipRect(0,0,400,400);
        canvas.drawColor(Color.BLUE);
        canvas.restore();

        paint.setColor(Color.BLUE);
        paint.setStyle(Paint.Style.STROKE);
        canvas.translate(10, 10);
        canvas.drawRect(0, 0, 300, 300, paint);
        paint.setColor(Color.RED);
        canvas.drawRect(200, 200, 400, 400,paint);
        invalidate();
    }
}
原文地址:https://www.cnblogs.com/bbglz/p/4794519.html