来自类的setwallpaper扩展了视图

时间:2013-12-03 12:09:17

标签: android view bitmap wallpaper

我正在尝试从我的类扩展视图超类的setwallpaper,我试图将视图转换为位图,但我收到一个错误(NullPointerException)。

case R.id.wallpaper: // This is an event of my button

        View view = new CustomWallpaper(this);


        b = convertToBitmap(view);

        WallpaperManager myWallpaperManager
         = WallpaperManager.getInstance(getApplicationContext());

        try {
            myWallpaperManager.setBitmap(b);
            new CustomToast(context, "Wallpaper has been set").show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        break;

这是我的方法

private Bitmap convertToBitmap(View view) {
    // TODO Auto-generated method stub

    Bitmap viewCapture = null;

    view.setDrawingCacheEnabled(true);

    viewCapture = Bitmap.createBitmap(view.getDrawingCache());

    view.setDrawingCacheEnabled(false);

    return viewCapture;
}

这是我的类,它扩展了视图

public class CustomWallpaper extends View {

public CustomWallpaper(Context context) {
    super(context);
    // TODO Auto-generated constructor stub

    setBackgroundColor(Color.BLACK);

    LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);

    setLayoutParams(params);
}

@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);

    Paint paint = new Paint();

    paint.setColor(Color.RED);

    canvas.drawCircle(50, 50, 30, paint);

}

}

谢谢

2 个答案:

答案 0 :(得分:1)

        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null) {
        bgDrawable.draw(canvas);
    } else {
        canvas.drawColor(Color.WHITE);
    }
    view.draw(canvas);

你的位图是returnBitmap

答案 1 :(得分:1)

然后无需创建CustomView。试试这个。它可以帮助你...

public void onClick(View view) {
    switch (view.getId()) {
    case R.id.wallpaper:
        Bitmap bitmap = getWallPaperBitmap();
        .......
        wallPaperManager.setBitmap(bitmap);
        break;

    default:
        break;
    }
}

public static Bitmap getWallPaperBitmap() {
    Bitmap bitmap = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawARGB(0, 0, 0, 0);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.RED);
    // this style will fill the circle
    paint.setStyle(Paint.Style.FILL);
    // this style will draw Circle path.
    paint.setStyle(Paint.Style.STROKE);
    canvas.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, 40, paint);
    return bitmap;
}