如何在屏幕中间绘制ImageView? (编程)

时间:2011-10-03 08:48:54

标签: android imageview

我想在屏幕中间水平和垂直绘制一个简单的ImageView。但是我想在不使用XML文件的情况下这样做,我需要以编程方式进行。

我尝试使用下一个代码,但它不能正常工作,它会将图像稍微向右和向下绘制一点。怎么解决?

    ARImage = new ImageView(getApplicationContext());
    ARImage.setImageResource(R.drawable.x);
    rl.addView(ARImage); //rl is the relative layout that it's inserted into a frame layout

    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    int w = display.getWidth();
    int h = display.getHeight();
    RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    position.leftMargin = (int)(w/2);
    position.topMargin  = (int)(h/2);
    ARImage.setLayoutParams(position);

4 个答案:

答案 0 :(得分:2)

这对我有用:

package pete.android.study;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;


public class Main extends Activity {

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView ARImage = new ImageView(getApplicationContext());
        ARImage.setImageResource(R.drawable.icon);
        RelativeLayout rl = new RelativeLayout(this);
        Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();
        RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ARImage.setLayoutParams(position);  

        position.addRule(RelativeLayout.CENTER_IN_PARENT);
        rl.addView(ARImage, position);  
        setContentView(rl); 
    }

}

答案 1 :(得分:1)

尝试使用

position.leftMargin = (int)(w/2 - whalf);
position.topMargin  = (int)(h/2 - hhalf);

其中whalfhhalf是图片参数的一半。

答案 2 :(得分:0)

我认为你不能设置左边和上边距:

position.leftMargin = (int)(w/2);
position.topMargin  = (int)(h/2);

尝试设置这样的边距:

position.setMargins((int)(w/2), (int)(h/2), 0, 0); // left, top, right, bottom

答案 3 :(得分:0)

知道它在RelativeLayout中,你可以把它放在这个布局的中心:

  RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  lp.addRule(RelativeLayout.CENTER_IN_PARENT);
  rl.addView(ARImage, lp);