【问题标题】:set position of programmatically created imageview android设置以编程方式创建的imageview android的位置
【发布时间】:2013-10-11 23:32:39
【问题描述】:

我只是想将我的 imageView 定位在屏幕上所需的位置,但由于某种原因,图片总是有点偏离,它不在正确的位置。例如,如果我想把它放在屏幕中间,这就是我的代码。

获取屏幕尺寸:

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;

获取图片大小:

    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.car1, o);
    int w = bmp.getWidth();
    int h = bmp.getHeight();

创建和定位 imageView:

    image = new ImageView(this);


    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.MATCH_PARENT,
                            RelativeLayout.LayoutParams.MATCH_PARENT);

    image.setScaleType(ImageView.ScaleType.MATRIX);
    image.setImageResource(R.drawable.car1);
    image.setId(1);


    params.setMargins((width/2)-w,(height/2)-h, 0, 0);


    ((ViewGroup) mainLayout).addView(image, params);

我的 imageView 不在屏幕中间,我不知道为什么,有什么帮助吗?我以屏幕中间为例;我需要各种职位。

【问题讨论】:

    标签: java android android-imageview


    【解决方案1】:

    我不确定 ImageView 的锚点是在图像的中间还是左上角。如果是左上角,则需要修改保证金计算:

    params.setMargins((width-w)/2,(height-h)/2, 0, 0);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-06
      • 2012-09-03
      • 2015-06-09
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多