2

我正在尝试剪切图像视图,现在我已经创建了一个自定义组件。这是代码:

package it.patrick91.eventually;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class CutImageView extends ImageView {
    private Path clipPath;
    private int type = 0;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        Log.d("cut", new Integer(type).toString());
        this.type = type;
    }

    public CutImageView(Context context) {
        super(context);
    }

    public CutImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.CutImageView);

        setType(a.getInt(R.styleable.CutImageView_type, 0));
    }

    public CutImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.CutImageView);

        setType(a.getInt(R.styleable.CutImageView_type, 0));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Log.d("cut", "size changed " + w + " " + h);
        clipPath = new Path();
        if (type == 0) {
            clipPath.moveTo(0, 0);
            clipPath.lineTo(0, h);
            clipPath.lineTo(w, 0);
            clipPath.lineTo(0, 0);
        } else {
            clipPath.moveTo(w, 0);
            clipPath.lineTo(w, h);
            clipPath.lineTo(0, h);
        }
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //canvas.clipPath(clipPath);
        super.onDraw(canvas);

        Bitmap rounder = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(rounder);    

        Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        xferPaint.setColor(Color.BLACK);


            c.drawPath(clipPath, xferPaint);

            xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvas.drawBitmap(rounder, 0, 0, xferPaint);
    }

}

所以我基本上使用 xfer 方法,如this answer所示。

问题是被擦除的部分是黑色的。正如我从该答案的评论中看到的那样,我必须确保我处于 ARGB 绘图上下文中,但我不确定我是否可以在 ImageView 的子类中做到这一点。你能帮助我吗?

这就是我得到的:

在此处输入图像描述

4

0 回答 0