【发布时间】:2011-10-14 00:15:40
【问题描述】:
我是 Android 图形的新手(尽管我非常精通 Android 编程本身)。我正在尝试在我的应用程序中显示一个“灯泡”。基于一些值,我想改变灯泡的“亮度”。
我为此使用了 PNG 图像。
<View
android:id="@+id/view2"
android:layout_width="59dp"
android:layout_height="65dp"
android:background="@drawable/lightbulb" />
而且,代码是这样的:
final View normalView = findViewById(R.id.view2);
//Where I need to set the alpha
int alphaValue = /*Some calculation*/
normalView.getBackground().setAlpha(alphaValue);
normalView.invalidate();
png 文件是一个透明图形,只有黑色的灯泡轮廓。现在,当我将 alpha 设置为较低的值(接近 0)时,会发生什么,整个图形变得透明。我只希望 灯泡的内容 变得透明。我希望灯泡的轮廓保持可见。
我确实尝试如下创建我的自定义视图,但现在我根本看不到图形。
class LightbulbView extends View {
private BitmapDrawable mLightbulbDrawable;
private Paint mPaint;
/*All constructors which call through to super*/
private void initialize(){
mLightbulbDrawable = new BitmapDrawable(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.lightbulb));
mPaint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mLightbulbDrawable.draw(canvas);
}
/*Without this, I get an NPE when I do a getBackground on this view*/
@Override
public Drawable getBackground() {
return mLightbulbDrawable;
//return super.getBackground();
}
}
当然,使用 ImageView 也没有什么好处。结果完全一样。
<ImageView
android:layout_width="wrap_content"
android:id="@+id/imageView1"
android:layout_height="wrap_content"
android:src="@drawable/lightbulb"
></ImageView>
这是代码
final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setAlpha(alphaValue);
那么,在 Android 中最好的方法是什么?
解决方案
我就是这样做的。请参阅接受的答案(@Petrus)了解更多详情:
<FrameLayout
android:id="@+id/frameLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView
android:layout_height="wrap_content"
android:src="@drawable/lightbulb_content"
android:layout_width="wrap_content"
android:id="@+id/bulbContent"
></ImageView>
<ImageView
android:layout_height="wrap_content"
android:src="@drawable/lightbulb"
android:layout_width="wrap_content"
android:id="@+id/bulb"
></ImageView>
</FrameLayout>
在代码中:
final ImageView bulbContent = (ImageView) findViewById(R.id.bulbContent);
//Where I need to set the alpha
int alphaValue = /*Some calculation*/
normalView.getBackground().setAlpha(alphaValue);
bulbContent.setAlpha(alphaValue);
这里,lightbulb.png 是一个只有灯泡轮廓的图像; lightbulb_content.png 是包含灯泡“内容”的图像。
【问题讨论】:
标签: android graphics bitmap alpha