如何根据屏幕分辨率更改点的位置?

时间:2012-12-21 10:04:35

标签: android

假设我把一些点作为(x1,y1)=(133,123),(x2,y2)=(149,136),(x3,y3)=(182,136)等等,这使得形状像这样: enter image description here enter image description here

现在我想根据屏幕分辨率更改这些点的位置,以便调整形状并使其居中,并且不会损坏形状。请帮帮我。

2 个答案:

答案 0 :(得分:2)

您可以从DisplayMetrics抓取比例因子,如Android - Supporting Multiple Screens文档中所示:

final float scale = getResources().getDisplayMetrics().density;

将所有x和y坐标乘以scale,并且您的点与屏幕密度无关。

要使图像适合屏幕(或者可能是View),您可以获取视图的widthheight。检查图像的宽度和高度,并计算最大比例因子。

合并(乘)两个比例因子,您的图像应符合您的视图。

答案 1 :(得分:1)

您可以使用onMeasure方法获取度量,然后您可以开始使用该位置进行绘制。我不知道下面的代码是否正常工作,也许需要进行优化。

protected void onDraw(Canvas canvas) {
        int height = getMeasuredHeight();
        int width = getMeasuredWidth();

        // Find the center
        px = width / 2;
        py = height / 2;

        canvas.drawColor(BACKGROUND);
        canvas.drawBitmap(mBitmap, 0, 0, null);
        canvas.drawPath(mPath, mPaint);

        // TODO remove if you dont want points to be drawn
        for (Point point : mPoints) {
            canvas.drawPoint(point.x + px, point.y + py, mPaint);
        }
    }




@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int measuredHeight = measureHeight(heightMeasureSpec);
        int measuredWidth = measureWidth(widthMeasureSpec);

        setMeasuredDimension(measuredHeight, measuredWidth);
    }

    private int measureHeight(int measureSpec) {
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        // Default size if no limits are specified.
        int result = 500;

        if (specMode == MeasureSpec.AT_MOST) {
            // Calculate the ideal size of your
            // control within this maximum size.
            // If your control fills the available
            // space return the outer bound.
            result = specSize;
        } else if (specMode == MeasureSpec.EXACTLY) {
            // If your control can fit within these bounds return that value.
            result = specSize;
        }
        return result;
    }

    private int measureWidth(int measureSpec) {
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        // Default size if no limits are specified.
        int result = 500;

        if (specMode == MeasureSpec.AT_MOST) {
            // Calculate the ideal size of your control
            // within this maximum size.
            // If your control fills the available space
            // return the outer bound.
            result = specSize;
        } else if (specMode == MeasureSpec.EXACTLY) {
            // If your control can fit within these bounds return that value.
            result = specSize;
        }

        return result;
    }