解决canvas.clipRegion 方法过时,实现裁剪减动画

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010853130/article/details/85076887

  最近想做一个图片裁剪的特效,发现原来的api :canvas.clipRegion过时了,

过期了我旧换一个好了,例如,clipRect,clipPath,下面就用clipPath实现

 废话不说代码如下:

package com.yuzy.test;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

import android.view.View;


public class ClipRgnView extends View {

    private Bitmap mBitMap;
    private int clipWidth=120;
    private int width;
    private int height;
    private Path mPath;
    private static final int CLIP_HEIGHT=30;
    private Rect mRect;
    
    public ClipRgnView(Context context) {
        super(context);
        init();
    }



    public ClipRgnView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ClipRgnView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public ClipRgnView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        mPath=new Path();
        //先关闭硬件加速
        setLayerType(LAYER_TYPE_SOFTWARE,null);
        mBitMap=BitmapFactory.decodeResource(getResources(),R.drawable.avant);
        width=mBitMap.getWidth();
        height=mBitMap.getHeight();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPath.reset();
    //  先画出裁剪区域
        int i=0;
        while(i*CLIP_HEIGHT<=height){

            if(i%2==0){
                //替换了Region.union方法
                 mPath.addRect(new RectF(0,i*CLIP_HEIGHT,clipWidth,(i+1)*CLIP_HEIGHT),Path.Direction.CCW);
             }else{
                 mPath.addRect(new RectF(width,i*CLIP_HEIGHT,width-clipWidth,(i+1)*CLIP_HEIGHT),Path.Direction.CCW);

             }

           i++;
        }
        //替换了canvas.clipRegion(region)
        canvas.clipPath(mPath);
        canvas.drawBitmap(mBitMap,0,0,new Paint());
        if(clipWidth>width){
            return;
        }
        clipWidth+=50;
        postInvalidate();
    }
}

 

展开阅读全文

没有更多推荐了,返回首页