Android支持的颜色系统是RGB,Alpha最后的Alpha表示透明度,他的取值是0-255,。通过设置Alpha的值,我们可以改变图像的透明度。
下面举例说明,效果图如下:
public class MainActivity extends Activity implements OnSeekBarChangeListener{ public static int alpha=100; private View myView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linearLayout=new LinearLayout(this); linearLayout.setOrientation(LinearLayout.VERTICAL); myView=new MyView(this); myView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 260)); SeekBar seekBar=new SeekBar(this); seekBar.setMax(255); //seekbar的初始值 seekBar.setProgress(alpha); seekBar.setOnSeekBarChangeListener(this); linearLayout.addView(myView); linearLayout.addView(seekBar); linearLayout.setBackgroundColor(color.white); setContentView(linearLayout); setTitle("Alpha"+alpha); } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub alpha=progress; setTitle("Alpha:"+alpha); myView.invalidate(); } private class MyView extends View{ private Bitmap bitmap; public MyView(Context context) { super(context); // TODO Auto-generated constructor stub InputStream is=getResources().openRawResource(R.drawable.ic_launcher); bitmap=BitmapFactory.decodeStream(is); setBackgroundColor(color.white); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub Paint paint=new Paint(); paint.setAlpha(alpha); //第二个参数表示源位图的复制区域,第三个参数表示绘制的目标区域 canvas.drawBitmap(bitmap, new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()),new Rect(10,10,310,235), paint); } } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } }