将ImageView资源设置为Drawable

时间:2010-05-02 21:26:14

标签: android android-layout android-image

我正在尝试在代码中创建一个drawable并根据某些条件更改颜色。当我尝试将Drawable设置为它所显示的ImageView的背景但不会让我设置任何填充。我意识到我需要通过setImageDrawable()函数设置ImageView图像,以便能够设置填充。

我遇到的问题是,当我通过setImageDrawable()函数设置它时,不会显示任何内容。

这是我写的:

<?xml version="1.0" encoding="utf-8"?>

            ImageView icon = (ImageView) row.findViewById(R.id.icon);
  ShapeDrawable mDrawable;

  int x = 0;
     int y = 0;
     int width = 50;
     int height = 50;

     float[] outerR = new float[] { 12, 12, 12, 12, 12, 12, 12, 12 };

     mDrawable = new ShapeDrawable(new RoundRectShape(outerR, null, null));
     mDrawable.setBounds(x, y+height, x + width, y);



  switch(position){

  case 0:
   mDrawable.getPaint().setColor(0xffff0000);  //Red
   break;
  case 1:
   mDrawable.getPaint().setColor(0xffff0000);  //Red
   break;
  case 2:
   mDrawable.getPaint().setColor(0xff00c000);  //Green
   break;
  case 3:
   mDrawable.getPaint().setColor(0xff00c000);  //Green
   break;
  case 4:
   mDrawable.getPaint().setColor(0xff0000ff);  //Blue
   break;
  case 5:
   mDrawable.getPaint().setColor(0xff0000ff);  //Blue
   break;
  case 6:
   mDrawable.getPaint().setColor(0xff696969);  //Gray
   break;
  case 7:
   mDrawable.getPaint().setColor(0xff696969);  //Gray
   break;
  case 8:
   mDrawable.getPaint().setColor(0xffffff00);  //Yellow
   break;
  case 9:
   mDrawable.getPaint().setColor(0xff8b4513);  //Brown
   break;
  case 10:
   mDrawable.getPaint().setColor(0xff8b4513);  //Brown
   break;
  case 11:
   mDrawable.getPaint().setColor(0xff8b4513);  //Brown
   break;
  case 12:
   mDrawable.getPaint().setColor(0xffa020f0);  //Purple
   break;
  case 13:
   mDrawable.getPaint().setColor(0xffff0000);  //Red
   break;
  case 14:
   mDrawable.getPaint().setColor(0xffffd700);  //Gold
   break;
  case 15:
   mDrawable.getPaint().setColor(0xffff6600);  //Orange
   break;
  }

     icon.setImageDrawable(mDrawable);
     icon.setPadding(5, 5, 5, 5);

这会导致ImageView的空间,但没有图像。

谢谢, 罗布

1 个答案:

答案 0 :(得分:0)

如果您实现自定义ImageView的绘制方法,则只需在图像上绘制一个色调即可。为了一个美好的玫瑰色光泽尝试:

    @Override
    protected void onDraw( Canvas canvas ) {
        super.onDraw( canvas );

        Rect                frame;
        Paint               paint = new Paint();

        paint.setStyle( Style.FILL );
        paint.setARGB( 102 , 255 , 51 , 51 );
        frame = new Rect( 0, 0, getWidth(), getHeight() );
        canvas.drawRect( frame , paint );
    }