- Home ›
- Android入門 ›
- ImageViewクラス ›
- HERE
透明度を設定
広告
表示される画像の透明度を設定する方法を確認します。「ImageView」クラスで用意されている「setAlpha」メソッドを使います。
setAlpha public void setAlpha(int alpha)
Parameters: alpha 透明度を表す数値
1番目の引数に透明度を表す数値を0から255までの値で指定します。0に近ければ透明度が高く、255に近づけば非透明となっていきます。
具体的には次のように記述します。
private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
ImageView image = new ImageView(this);
image.setImageResource(R.drawable.bitmapsample);
image.setAlpha(100);
setContentView(image, new LayoutParams(WC, WC));
}
サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
package jp.javadrive.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.content.Resources;
import java.io.IOException;
public class Test04_01 extends Activity
{
private final int FP = ViewGroup.LayoutParams.FILL_PARENT;
private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setBackground(R.drawable.flower);
setContentView(linearLayout);
ImageView image1 = new ImageView(this);
image1.setImageResource(R.drawable.star1);
image1.setAlpha(50);
linearLayout.addView(image1, createParam(WC, WC));
ImageView image2 = new ImageView(this);
image2.setImageResource(R.drawable.star1);
image2.setAlpha(160);
linearLayout.addView(image2, createParam(WC, WC));
ImageView image3 = new ImageView(this);
image3.setImageResource(R.drawable.star1);
image3.setAlpha(255);
linearLayout.addView(image3, createParam(WC, WC));
}
private LinearLayout.LayoutParams createParam(int w, int h){
return new LinearLayout.LayoutParams(w, h);
}
}
また画像をリソースとしてプロジェクト内の「res/drawable」ディレクトリに配置しました。
ビルド後にエミュレーター上で実行します。
左から右へ向かって透明度を表す数値を大きくしてあります。
( Written by Tatsuo Ikura )
JavaDrive