Android画布:线条和椭圆尺度,但路径不是吗?

时间:2014-07-25 19:59:53

标签: android android-canvas

我在我的应用程序中使用方形帆布,我的目标是在0.0 / 0.0(左上角)和1.0 / 1.0(右下角)之间绘制所有内容,以便我可以稍后将其缩放,具体取决于在屏幕尺寸上。

这适用于某些基本绘图方法,但不适用于路径。我的onDraw-method:

@Override
protected void onDraw(Canvas canvas) {
    canvas.scale(getWidth(), getWidth());
    canvas.drawOval(outerRect, linePaint);
    canvas.drawLine(0.5f, 0.05f, 0.5f, 0.95f, linePaint);
    canvas.drawPath(trianglePath, linePaint);
}

outerRect和trianglePath的定义:

outerRect = new RectF(0.05f, 0.05f, 0.95f, 0.95f);

trianglePath = new Path();
trianglePath.moveTo(0.05f, 0.05f); 
trianglePath.lineTo(0.95f, 0.05f);
trianglePath.lineTo(0.5f, 0.95f);
trianglePath.close();

如您所见,结果中没有三角形:

enter image description here

为什么?

编辑:整个视图

public class PlaygroundView extends View {

    private Paint linePaint;
    private RectF outerRect;
    private Path trianglePath;

    private final int preferredSize = 300;

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

    private void init() {

        outerRect = new RectF(0.05f, 0.05f, 0.95f, 0.95f);

        trianglePath = new Path();
        trianglePath.reset();
        trianglePath.moveTo(0.05f, 0.05f); 
        trianglePath.lineTo(0.95f, 0.05f);
        trianglePath.lineTo(0.5f, 0.95f);
        trianglePath.close();

        linePaint = new Paint();
        linePaint.setColor(Color.WHITE);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setStrokeWidth(0.01f);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int chosenWidth = chooseDimension(widthMode, widthSize);
        int chosenHeight = chooseDimension(heightMode, heightSize);

        int chosenDimension = Math.min(chosenWidth, chosenHeight);

        setMeasuredDimension(chosenDimension, chosenDimension);
    }

    private int chooseDimension(int mode, int size) {
        if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
            return size;
        } else { // (mode == MeasureSpec.UNSPECIFIED)
            return preferredSize;
        }
    }


    @Override
    protected void onDraw(Canvas canvas) {
        canvas.scale(getWidth(), getWidth());
        canvas.drawOval(outerRect, linePaint);
        canvas.drawLine(0.5f, 0.05f, 0.5f, 0.95f, linePaint);
        canvas.drawPath(trianglePath, linePaint);
    }
}

编辑#2:

嗯,这很奇怪。新创建的模拟器实例显示圆和线,但不显示三角形,而IDE预览显示三角形,但不显示圆和线。两者都基于我多次重建的相同代码......

enter image description here

0 个答案:

没有答案