美文网首页
Android maskImageview,自定义蒙版图片控件2

Android maskImageview,自定义蒙版图片控件2

作者: Colin高宏杰 | 来源:发表于2018-08-02 11:00 被阅读0次

public class MaskImageextends ImageView {

int mImageSource =0;

    int mMaskSource =0;

    RuntimeExceptionmException;

    TypedArraya;

    public MaskImage(Context context, AttributeSet attrs) {

super(context, attrs);

        a = getContext().obtainStyledAttributes(attrs, R.styleable.MaskImage, 0, 0);

    }

public void mask(int imageing,int masking){

mImageSource = imageing;

        mMaskSource = masking;

        if (mImageSource ==0 ||mMaskSource ==0) {

mException =new IllegalArgumentException(a.getPositionDescription() +

": The content attribute is required and must refer to a valid image.");

        }

if (mException !=null)

throw mException;

        /**

* 主要代码实现

*/

        //获取图片的资源文件

        Bitmap original = BitmapFactory.decodeResource(getResources(), mImageSource);

        int width = original.getWidth();

        int height = original.getHeight();

        int newWidth =402;

        int newHeight =402;

        float scaleWidth = ((float) newWidth) / width;

        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix =new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);

        Bitmap newbm = Bitmap.createBitmap(original, 0, 0, width, height, matrix, true);

        //获取遮罩层图片

        Bitmap mask = BitmapFactory.decodeResource(getResources(), mMaskSource);

        Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Config.ARGB_8888);

        //将遮罩层的图片放到画布中

        Canvas mCanvas =new Canvas(result);

        Paint paint =new Paint(Paint.ANTI_ALIAS_FLAG);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));//叠加重复的部分,显示下面的

        mCanvas.drawBitmap(newbm, 0, 0, null);

        mCanvas.drawBitmap(mask, 0, 0, paint);

        paint.setXfermode(null);

        setImageBitmap(result);

        setScaleType(ScaleType.CENTER);

//        a.recycle();

    }

}

  蒙版实现效果(需要ui切10张图。蒙版的方块线条一个,alpha通道图片九张。

如下图:


相关文章

网友评论

      本文标题:Android maskImageview,自定义蒙版图片控件2

      本文链接:https://www.haomeiwen.com/subject/hadjvftx.html