canvas.getDrawingCache() 返回 null - Android

canvas.getDrawingCache() returning null - Android

我在这个 class 中为 canvas ViewCanvas 设置了单独的 class 我正在绘制两个世界。这是代码:

public class ViewCanvas extends View {

    private Paint paint;
    private Typeface typeFace;

    public ViewCanvas(Context context) {
        super(context);
    }

    public ViewCanvas(Context context, String first, String second) {
        super(context);

        setDrawingCacheEnabled(true);
        buildDrawingCache(true);
        paint = new Paint();
        typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/BigNoodleTitling.ttf");
        bounds = new Rect();
    }

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

        paint.setColor(Color.BLACK);
        paint.setTextSize(20);
        paint.setTypeface(typeFace);

        // Closing hardware acceleration
        setLayerType(LAYER_TYPE_SOFTWARE, paint);

        // Drawing first word
        canvas.save();
        .
        .
        .
        .
        // Drawing second world
        canvas.restore();
        .
        .
        .
        .
    }
}

这段代码工作正常。我在 MainActivity 中使用这个 ViewCanvas 是这样的:

public class MainActivity extends Activity {

    private ViewCanvas viewCanvas;
    private Bitmap imageForShare;

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

        viewCanvas = new ViewCanvas(this, first, second);
        LinearLayout llCanvas = (LinearLayout) findViewById(R.id.llCanvas);
        llCanvas.addView(viewCanvas);


        imageForShare = viewCanvas.getDrawingCache();
}

这里imageForShare为null,不知道为什么。

在我的 onClick 方法中,viewCanvas.getDrawingCache() 运行良好。 imageForShare 不为空,我可以使用它。这是我的代码:

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnFacebook:
            imageForShare = viewCanvas.getDrawingCache();
            break;
    }
}

问题出在哪里,我希望在我的onCreate方法中提供imageForShare。

试试这个:

public static Bitmap loadBitmapFromView(View v) {
     Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
     Canvas c = new Canvas(b);
     v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
     v.draw(c);
     return b;
}

link

能不能不用OnStart()来截图?
activity 的可见生命周期发生在对 onStart()

的调用之间

好的,我找到了解决办法。在 onCreate 方法中创建 imageForShare 是不可能的,因为 canvas 是在创建 imageForShare 之后绘制的。所以我在 onWindowFocusChanged 中创建了 imageForShare,并且效果很好:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    imageForShare = viewCanvas.getDrawingCache(); 
}