缩放后无法drawArc

时间:2014-04-02 10:26:32

标签: android canvas

我是Android开发和画布绘图的新手。 当我在画布上绘制东西时,我更容易在width = height = 1的矩形部分上工作。

我尝试按比例缩放,但在尝试绘制Arc时,它的绘制效果非常糟糕。 你能告诉我我做错了什么吗?

public class MyChart extends View{
    private RectF dimentionRect;
    private Paint dimentionPaint;
    private static final String TAG = "VERBOSE";
    public MyChart(Context context){
        super(context);
        initDrawingTools();
    }
    public MyChart(Context context,AttributeSet attrs) {
        super(context,attrs);
        initDrawingTools();
    }

    private void initDrawingTools(){
        dimentionPaint = new Paint();
        dimentionPaint.setColor(Color.GREEN);
        dimentionPaint.setStyle(Style.FILL);
    }
    @Override
    protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int chosenDimention = Math.min(widthSize, heightSize);
        setMeasuredDimension(chosenDimention, chosenDimention);
        Log.v(TAG, "onMeasure: "+chosenDimention);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Log.v(TAG, "onSizeChange");
    }

    @Override
    public void onDraw(Canvas canvas){
        float width = (float)getWidth();
        Log.v(TAG, "onDraw: "+width);

        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.scale(width, width);

        dimentionRect = new RectF(0,0,1f,1f);
        //canvas.drawRect(dimentionRect, dimentionPaint); //
        canvas.drawArc(dimentionRect, 0, 180, true, dimentionPaint);
    //  canvas.drawCircle(0.5f, 0.5f, 0.3f, dimentionPaint);
        canvas.restore();

    }

}

1 个答案:

答案 0 :(得分:0)

好的,我没有找到解决方案,但我找到了解决办法。 我创建了一个背景位图,并将其用于执行绘图工作的本地Canvas。在所有绘图之后,我再次将位图绘制到我的画布中。 我知道它不优雅,但这就是我找到的解决方案

private void drawBackground(Canvas canvas){
        if(background != null){
            canvas.drawBitmap(background, 0,0,backgroundPaint);
            Log.e(TAG, "Drawing background");
        }
    }

    private void regenerateBackground(){
        if(background != null){
            background.recycle();
        }
        background = Bitmap.createBitmap(getWidth(), getWidth(), Config.ARGB_8888);
        RectF rect = new RectF(0,0,getWidth(),getWidth());
        Canvas c = new Canvas(background);
        c.drawRect(rect, backgroundPaint);

    }
    @Override 
    protected void onDraw(Canvas canvas){
        drawBackground(canvas);

        float width = (float)getWidth();
        Canvas c = new Canvas(background);

        c.save(Canvas.MATRIX_SAVE_FLAG);
        c.scale(width,width);
        border = new RectF(0,0,1,1);
//      
        Paint p = new Paint();
        p.setColor(Color.GREEN);
        p.setStyle(Style.FILL);
        c.drawArc(border, 0, 360,true, p);
        c.restore();

    }