获取视图中心的坐标

时间:2013-10-27 07:36:01

标签: android android-view android-location

我正在尝试获取自定义视图(圆圈)的中心坐标,以便我可以从这些点中绘制一条线。自定义视图位于TableLayout内,FrameLayout位于public float[] getDotCenterLocationOnScreen() { int[] location = new int[2]; getLocationOnScreen(location); int xLoc = location[0]; int yLoc = location[1]; float xCenter = xLoc + (getWidth()/2); float yCenter = yLoc - (getWidth()/2); float[] dotCenterLocation = { xCenter, yCenter }; return dotCenterLocation; } 内。但是,我遇到了麻烦 - 这段代码并不正确。有什么建议吗?

此方法给出的值在所有设备上都是错误的。如果我更改了布局填充/边距等,那么这些点显然会移动,但此方法给出的点不会改变。

        // Radius of Dot
        int RADIUS;
        private static final int START_RADIUS = 30;

        // Value of which the Radius is multiplied by to get full width & height of
        // the DotView
        int sizeMultiplier = 4;

        // Define other Objects
        private Paint paint = new Paint();      

        float mTranslateX;
        float mTranslateY;

        public DotView(Context context, AttributeSet attrs) {
            super(context, attrs);

            paint.setAntiAlias(true);
            paint.setStrokeWidth(6f);
            paint.setStyle(Paint.Style.FILL);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setColor(Color.BLACK);

            RADIUS = START_RADIUS;

        }

        public void setRadius(int radius) {
            RADIUS = radius;
            invalidate();
        }

        public int getRadius() {
            return RADIUS;
        }

        public void onDraw(Canvas canvas) {

            super.onDraw(canvas);
            canvas.save();
            canvas.translate(mTranslateX, mTranslateY);
            canvas.drawCircle(0, 0, RADIUS, paint);
            canvas.restore();
        }

        public float[] getDotCenterLocationOnScreen() {

            int[] location = new int[2];
            getLocationOnScreen(location);

            int xLoc = location[0];
            int yLoc = location[1];

            float xCenter = xLoc + (getWidth()/2);
            float yCenter = yLoc - (getWidth()/2);

            float[] dotCenterLocation =  { xCenter, yCenter };

            return dotCenterLocation;

        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            final int dia = START_RADIUS * sizeMultiplier; // Multiplying by 2 makes
                                                            // boundaries exactly the same size a dot.

            int w = resolveSize(dia, widthMeasureSpec);
            int h = resolveSize(dia, heightMeasureSpec);
            setMeasuredDimension(w, h);
            float radius = Math.min(w, h) / 2F;
            mTranslateX = radius;
            mTranslateY = radius;
}

    }

以下是我的视图类中的大部分代码:

{{1}}

0 个答案:

没有答案