سؤال

I am trying to setwallpaper from my class which extends view superclass , i am trying to convert view into the bitmap but i am getting an error (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;

and this is my method

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;
}

And this is my class which extends view

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);

}

}

Thank You

هل كانت مفيدة؟

المحلول

then no need to create CustomView. try this. it may help you...

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;
}

نصائح أخرى

        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);

and your bitmap is returnedBitmap

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top