Android使用代码创建可绘制图像

时间:2014-01-07 15:42:38

标签: android android-imageview android-drawable

我需要能够通过代码创建自定义图像,然后将该图像设置为imageview

我希望此图片具有纯色背景色,标题和图标。 我希望它可以自定义,以便我可以调用以创建具有值的图像 例如

createImage(String bckgColourHex, String title, int iconResource){
 // create image using value here

return image.
}

然后我可以使用drawable将其设置为我的imageView

这是我到目前为止所尝试的

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView image = (ImageView) findViewById(R.id.imageView1);

        BitmapDrawable customImage = writeOnDrawable(R.drawable.background_gradient, "TEXT GOES HERE");
        image.setBackgroundDrawable(customImage);

    }


    public BitmapDrawable writeOnDrawable(int drawableId, String text){

        Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
        Paint paint = new Paint(); 
        paint.setStyle(Style.FILL);  
        paint.setColor(Color.BLACK); 
        paint.setTextSize(20); 

        Canvas canvas = new Canvas(bm);
        canvas.drawText(text, 0, bm.getHeight()/2, paint);

        return new BitmapDrawable(bm);
    }

谢谢

1 个答案:

答案 0 :(得分:1)

 public static Drawable makeBorderedDrawable(Context mContext, int width, String xCode, Boolean unAvail) {

    Paint p = new Paint();
    Bitmap bkg = null;
    final int FULL_ALPHA = 0xFF123456; // of whatever color you want

    int pixel = FULL_ALPHA;

    // first create a mutable bitmap
    bkg = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);

    Canvas c = new Canvas(bkg);

    p.setColor(pixel);
    c.drawCircle(width / 2, width / 2, width / 2, p);

    // or draw rect, or lines, or drawtext....or whatever


    return new BitmapDrawable(mContext.getResources(), bkg);

    // or you could return a Bitmap if you prefer.

}