使用xfer剪辑图像视图

时间:2012-08-07 22:43:07

标签: android android-canvas

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

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);
    }

}

所以我基本上使用了in this answer所示的xfer方法。

问题是删除部分是黑色的。正如我可以从该答案的评论中读到的,我必须确保我处于ARGB绘图上下文中,但我不确定我是否可以在ImageView的子类中执行此操作。你能救我吗?

这就是我得到的:

enter image description here

0 个答案:

没有答案