【问题标题】:Android: Make specific (green) color in background image transparentAndroid:使背景图像中的特定(绿色)颜色透明
【发布时间】:2011-07-06 13:46:43
【问题描述】:

我正在为 Android 编写一个应用程序。

在定义布局的 xml 文件中,我有一个带有 6 个选项卡的 TabHost,它们都有相同的大背景图像“settingsdlg.gif”。

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:background="@drawable/settingsdlg" >
..

在styles.xml中我指定窗口必须是透明的:

<resources>
    <style name="my_app_style"  parent="@android:style/Theme.Dialog">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
    </style>

问题是背景图像“settingsdlg.gif”是一个圆角矩形,边缘的小区域应该是透明的,是绿色的。

我知道要在Android上的图像中使用透明度,图像必须是PNG格式,我想要透明的像素应该保存为透明的PNG。

不幸的是,我从数据库中获取图像,但无法更改它们,因为它们也用于 Win32 和 Mac 的其他应用程序中。

有没有办法告诉 Android 背景图像中的绿色像素应该是透明的?

谢谢!

【问题讨论】:

    标签: android image background replace transparent


    【解决方案1】:

    您必须将每个绿色像素更改为透明像素。这是一个例子:How to change colors of a Drawable in Android?

    但是,如果图像中间有绿色像素,则可能会出现问题。所以另一种方法是,如果您的图像具有恒定的大小和形状,则创建蒙版并使用 xfer 模式创建具有透明圆角的新图像。

    【讨论】:

      【解决方案2】:

      如果有人遇到同样的问题,这里是代码:

      //remove green edges from bg image
          Bitmap bgBitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.settingsdlg)).getBitmap();
          Bitmap transparentBgBitmap = Utils.getBitmapWithTransparentBG(bgBitmap, Color.GREEN);
          tabHost.setBackgroundDrawable(new BitmapDrawable(transparentBgBitmap));
      

      在实用程序中:

      public static Bitmap getBitmapWithTransparentBG(Bitmap srcBitmap, int bgColor) {
          Bitmap result = srcBitmap.copy(Bitmap.Config.ARGB_8888, true);
          int nWidth = result.getWidth();
          int nHeight = result.getHeight();
          for (int y = 0; y < nHeight; ++y)
            for (int x = 0; x < nWidth; ++x) {
          int nPixelColor = result.getPixel(x, y);
          if (nPixelColor == bgColor)
            result.setPixel(x, y, Color.TRANSPARENT);
            }
          return result;
      }
      

      【讨论】:

        【解决方案3】:

        这段代码 sn-p 对我有用:

        PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(
            getResources().getColor(R.color.your_color),
            PorterDuff.Mode.MULTIPLY
        );
        imgView.getDrawable().setColorFilter(porterDuffColorFilter);
        imgView.setBackgroundColor(Color.TRANSPARENT);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-08
          • 1970-01-01
          • 2017-08-11
          • 2018-02-23
          • 2017-06-06
          • 1970-01-01
          相关资源
          最近更新 更多