Android位图 - 最佳实践

4

开发适用于任何屏幕尺寸的图形应用程序需要一些思考。通常,我创建高分辨率图形,然后按比例缩放以适应屏幕。

我看到了一个建议,避免使用“真实像素”。我尝试使用密度和dp进行工作,但似乎比我使用的解决方案更加复杂。而且,我找不到比使用设备屏幕(真实像素)更好的方法来缩放我的图形。

我创建了这个类来缩放我的图像(基于真实像素)。这解决了我大部分的问题(仍然有一些设备具有不同的纵横比),并且似乎运行良好。

public class BitmapHelper {
    // Scale and keep aspect ratio 
    static public Bitmap scaleToFitWidth(Bitmap b, int width) {
        float factor = width / (float) b.getWidth();
        return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), false);  
    }

    // Scale and keep aspect ratio     
    static public Bitmap scaleToFitHeight(Bitmap b, int height) {
        float factor = height / (float) b.getHeight();
        return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, false);  
    }

    // Scale and keep aspect ratio 
    static public Bitmap scaleToFill(Bitmap b, int width, int height) {
        float factorH = height / (float) b.getWidth();
        float factorW = width / (float) b.getWidth();
        float factorToUse = (factorH > factorW) ? factorW : factorH;
        return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorToUse), (int) (b.getHeight() * factorToUse), false);  
    }

    // Scale and dont keep aspect ratio 
    static public Bitmap strechToFill(Bitmap b, int width, int height) {
        float factorH = height / (float) b.getHeight();
        float factorW = width / (float) b.getWidth();
        return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorW), (int) (b.getHeight() * factorH), false);  
    }
}

我的问题是:
  1. 为什么建议避免使用“真实像素”?
  2. 缩放位图到屏幕的最佳实践是什么(欢迎提供好的教程文章)?
  3. 使用我目前的方法有哪些缺点,或者在使用这种方法时需要注意什么?
谢谢你的建议。
[编辑] 我忘了提到我通常会在我的应用程序中使用SurfaceView(如果有任何区别)。

还可以看看这个。在智能解码ByteArrays到位图的问题上,它会对你有所帮助。 - teoREtik
1个回答

0
  1. 不要追求像素完美的应用,因为它在其他分辨率上可能无法正常工作。当你创建良好可伸缩布局时,Android会自动处理图像大小,所以你不需要手动处理。你应该为所有dpi类型制作图像,并通过使用资源限定符(drawable-ldp文件夹、drawable-mdp文件夹等)将它们分开放置在你的资源中。
  2. 不要自己缩放位图,正如我所说,Android会为你完成这项工作。你可以影响Android缩放位图的方式,请参见http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType
  3. Android会为你计算正确的尺寸。这样,你就不必自己进行所有的数学计算来尝试让所有东西都显示在屏幕上。构建一个能在各种设备上运行的良好应用程序需要花费精力制作多组可绘制对象和可能的多组布局(横向/纵向、小屏幕/大屏幕等)。

有一件事我忘了提.. 我目前使用SurfaceView。这会有影响吗? - Nir
好的,我理解了“永远不要让应用程序完美无缺”的概念。但我不确定正确的方法是什么。例如,我创建了一个800x480像素的图像,这是我的设备分辨率。然后我使用DecodeBitmap(<res>)加载它,但“Android”自动将我的图像缩放到1200x720像素,我认为这是错误的决定。为什么?我该如何相信自动缩放呢? - Nir
800x480 对于您的屏幕是完美的,但在其他一些手机和平板电脑上则不是。在 XML 布局中,您应该使用不同种类的布局类型(RelativeLayout、LinearLayout、TableLayout 等),并以 DP 为单位提供尺寸,或使用 fill_parent 或 wrap_content。如果需要,可以添加一些权重。请阅读以下文章: http://developer.android.com/reference/android/view/View.html - Jordi
我想你忽略了我正在使用SurfaceView这一事实。我加载的图像通常是背景和精灵。如果“自动”加载在我的设备屏幕上出错,那么这是一个糟糕的起点 :( 这样我就无法在其他屏幕上控制我的应用程序。 - Nir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接