【问题标题】:How to get Center of an Imageview which is a circle如何获得一个圆圈的 Imageview 的中心
【发布时间】:2016-12-02 04:38:57
【问题描述】:

现在我有一个 ImgeView,它是一个圆圈,我想找到那个圆圈的中心点,所以我尝试了以下代码,但它似乎不起作用

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

int radius=imageView.getHeight()/2;
                    int[] center=new int[2];
                    center[0]=location[0]+radius;
                    center[1]=location[1]+radius;

所以我通过“位置”得到的坐标是不是图像视图的顶点?

请帮助我如何获得图像视图的中心点。

【问题讨论】:

    标签: android touch-event android-imageview


    【解决方案1】:

    我假设以下情况:

    您将加载一个 ImageView(从 xml 或代码)并在 myImageView(比如)中引用相同的内容。现在,您希望计算 myImageView 的中心,而不考虑它在屏幕上的位置。

    如果我的假设是正确的,那么下面可能就是您正在寻找的解决方案:

        int centerXOnImage=myImageView.getWidth()/2;
        int centerYOnImage=myImageView.getHeight()/2;
    
        int centerXOfImageOnScreen=myImageView.getLeft()+centerXOnImage;
        int centerYOfImageOnScreen=myImageView.getTop()+centerYOnImage;
    

    【讨论】:

    • 但是 myImageView.getLeft() 和 myImageView.getTop() 会根据其父级给出位置???
    • 其实我想实现如下链接目标** link** 或许你能更深入地理解我的问题
    【解决方案2】:

    您可以使用以下方法获取左上角坐标:

    ImageView iv = (ImageView)findViewById(R.id.image_view);
    Rect rect = iv.getDrawable().getRect();
    int xOffset = rect.left;
    int yOffset = rect.top;
    

    根据 height/2 和 width/2 您可以建立 ImageView 的中心。

    【讨论】:

    • 我想要中心点的 x,y 坐标和整个屏幕方向,因为我必须考虑整个屏幕在 Imageview 的中心点上工作
    【解决方案3】:

    除了 Chandan 的回答, 假设我们使用相同的代码:

    int centerXOnImage=myImageView.getWidth()/2;
    int centerYOnImage=myImageView.getHeight()/2;
    
    int centerXOfImageOnScreen=myImageView.getLeft()+centerXOnImage;
    int centerYOfImageOnScreen=myImageView.getTop()+centerYOnImage;
    

    如果您的 myImageView.getWidth() 返回 0,您可能需要进行一些修改:

    myImageView.measure(0,0);
    int centerXOnImage=myImageView.getMeasuredWidth()/2;
    int centerYOnImage=myImageView.getMeasuredHeight()/2;
    

    注意,您可能希望在 myImageView 在代码中创建并添加到根视图之后执行此操作。

    【讨论】:

    • myImageView.getHeight() 总是返回 0。为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多