我是Android的圖形新手(儘管我對Android編程本身非常精通)。我試圖在我的應用中顯示「燈泡」。基於一些價值觀,我想改變燈泡的「亮度」。Android圖形:改變只是一個圖像的alpha(不是背景)
我爲此使用了一個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中做到這一點的最好方法是什麼?
SOLUTION
這是我做到了。請參閱接受的答案(由@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是一個帶有燈泡「內容」的圖像。
完美!那就是訣竅。謝謝。 – curioustechizen