在android中使用图像而不是图像视图

时间:2015-01-21 02:28:00

标签: android android-canvas android-view android-custom-view android-drawable

我正在制作绘图板应用程序。我想实现一个画在图像上的“笔”。

到目前为止,我已经创建了一个自定义的imageview:

public class CustomDraw extends ImageView {

    private int color = Color.BLACK;
    private float width = 4f;
    private List<Holder> holderList = new ArrayList<Holder>();

    private class Holder {      
        Path path;
        Paint paint;

        Holder(int color, float width) {
            path = new Path();
            paint = new Paint();
            paint.setAntiAlias(true);
            paint.setStrokeWidth(width);
            paint.setColor(color);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeCap(Paint.Cap.ROUND);
        }
    }

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

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

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

    private void init() {
        holderList.add(new Holder(color, width));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (Holder holder : holderList) {
            canvas.drawPath(holder.path, holder.paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                holderList.add(new Holder(color,width));
                holderList.get(holderList.size() - 1).path.moveTo(eventX, eventY);
                return true;
            case MotionEvent.ACTION_MOVE:
                holderList.get(holderList.size() - 1).path.lineTo(eventX, eventY);
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                return false;
        }

        invalidate();
        return true;
    }

    public void resetPaths() {
        for (Holder holder : holderList) {
            holder.path.reset();
        }
        invalidate();
    }

    public void setBrushColor(int color) {
        this.color = color;
    }

    public void setWidth(float width) {
        this.width = width;
        }
}

问题是,我如何在图像上实际绘制而不是在imageview上绘图?这意味着,我不能在图像外部绘图,当我缩放视图时,内容应该相应地缩放。我发现并尝试使用extend drawable但似乎我无法在运行时绘制。

由于

1 个答案:

答案 0 :(得分:2)