【问题标题】:Android Changing image size depending on Screen Size?Android 根据屏幕尺寸更改图像尺寸?
【发布时间】:2011-06-15 11:06:58
【问题描述】:

所以我需要根据屏幕区域更改图像的大小。图片必须是屏幕高度的一半,否则它会与一些文本重叠。

所以高度= 1/2 屏幕高度。 Width = Height*Aspect Ratio(只是尽量保持纵横比不变)

我发现了一些东西:

Display myDisplay = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width =myDisplay.getWidth();
int height=myDisplay.getHeight();

但是如何在 java 中更改图像高度?如果可能的话,甚至是 XML?我似乎找不到有效的答案。

【问题讨论】:

    标签: android imageview screen-size


    【解决方案1】:

    您可以在代码中使用LayoutParams 执行此操作。不幸的是,没有办法通过 XML 指定百分比(不是直接指定,你可以乱用权重,但这并不总是有帮助,而且它不会保持你的纵横比),但这应该适合你:

    //assuming your layout is in a LinearLayout as its root
    LinearLayout layout = (LinearLayout)findViewById(R.id.rootlayout);
    
    ImageView image = new ImageView(this);
    image.setImageResource(R.drawable.image);
    
    int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2;
    int orgWidth = image.getDrawable().getIntrinsicWidth();
    int orgHeight = image.getDrawable().getIntrinsicHeight();
    
    //double check my math, this should be right, though
    int newWidth = Math.floor((orgWidth * newHeight) / orgHeight);
    
    //Use RelativeLayout.LayoutParams if your parent is a RelativeLayout
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        newWidth, newHeight);
    image.setLayoutParams(params);
    image.setScaleType(ImageView.ScaleType.CENTER_CROP);
    layout.addView(image);
    

    可能过于复杂,也许有更简单的方法?不过,这是我首先尝试的。

    【讨论】:

    • 如果我尝试运行它,我似乎会强制关闭。如果这有帮助,在 LogCat 下,我得到“未捕获的处理程序:线程主因未捕获的异常而退出”。我不完全确定这意味着什么。 Ps.我对 android 还是有点陌生​​
    • 嗯,这是一个通用示例,您的情况当然会有所不同(变量名称、XML id 等)。在 LogCat 下,它应该可以跟踪发生了什么异常,以及在文件的哪一行。
    • 啊……我知道我做错了什么,我用“R.id.rootlayout”代替了我的 ImageView,而不是我的 RelativeLayout.. 谢谢!!!!
    • 小错字,int orgHeight = image.getDrawable().getIntrinsicHeight();而不是宽度
    • @GeertWeening 谢谢,已修复。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 2013-02-05
    • 2015-02-28
    相关资源
    最近更新 更多