在一个Android应用中,我试图拍摄一个名为Sierpinski Triangle的视图的屏幕截图。但是,位图总是返回空值。 Sierpinski Triangle仅具有onDraw方法中的图形(无按钮,文本视图,背景...)这是我的代码:
sierpinskiTriangle.setDrawingCacheEnabled(true);
sierpinskiTriangle.buildDrawingCache(true);
sierpinskiTriangle.setDrawingCacheQuality(2);
sierpinskiTriangle.measure(MeasureSpec.makeMeasureSpec(50, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(50, MeasureSpec.UNSPECIFIED));
sierpinskiTriangle.layout(0, 0, sierpinskiTriangle.getMeasuredWidth(), sierpinskiTriangle.getMeasuredHeight());
Bitmap screensaver =sierpinskiTriangle.getDrawingCache(true);
Bitmap screenshot = Bitmap.createBitmap(this.sierpinskiTriangle.getWidth(), this.sierpinskiTriangle.getHeight(), Config.ARGB_8888);
请帮助,我已经花了几个小时了。
这是Sierpinski Triangle的代码:
package com.Marco.Fractal;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.view.View;
public class SierpinskiTriangle extends View{
Paint paint = new Paint();
int stage;
int width;
int height;
int h1, h2, w1, w2,w3;
public SierpinskiTriangle(Context context, int t, int s, int w, int h) {
super(context);
stage = s;
width=w;
height=h;
paint.setColor(Color.RED);
h1=(int)(height/2-((((width-30)/4)*1.732)));
h2=(int)(height/2+((((width-30)/4)*1.732)));
w1=15;
w2=width-15;
w3=width/2;
}
protected void onDraw(final Canvas canvas) {
this.setDrawingCacheEnabled(true);
this.buildDrawingCache(true);
canvas.drawLine(w1, h2, w3, (float) h1, paint);
canvas.drawLine(w2, h2, w3, (float) h1, paint);
canvas.drawLine(w1, h2, w2, h2, paint);
triangles(canvas, w1, h2, w3, h1, w2, h2, stage);
}
protected void triangles(final Canvas canvas, int x1, int y1, int x2, int y2, int x3, int y3, int r)
{
if(r==0)
{
canvas.drawLine(x1, y1, x2, y2, paint);
canvas.drawLine(x2, y2, x3, y3, paint);
canvas.drawLine(x3, y3, x1, y1, paint);
}
else
{
int xm1 = (x1+x2)/2;
int xm2 = (x2+x3)/2;
int xm3 = (x1+x3)/2;
int ym1 = (y1+y2)/2;
int ym2 = (y2+y3)/2;
int ym3 = (y1+y3)/2;
triangles(canvas, x1, y1, xm1, ym1, xm3,ym3, r-1);
triangles(canvas, xm3, ym3,xm2, ym2, x3, y3, r-1);
triangles(canvas, xm1, ym1, x2,y2, xm2,ym2,r-1);
}
}
}
最佳答案
[EDIT2]
我感到您的onDraw方法中的以下两行让您感到困惑:
this.setDrawingCacheEnabled(true);
this.buildDrawingCache(true);
尝试删除它们,看看会发生什么!!!
[EDIT1]
尝试从所有简单的事情中简化代码:
Bitmap screenshot;
sierpinskiTriangle.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(sierpinskiTriangle.getDrawingCache(true));
sierpinskiTriangle.setDrawingCacheEnabled(false);
[原版的]
尝试:
Bitmap screenshot = Bitmap.createBitmap(sierpinskiTriangle.getDrawingCache(true));
也请看这里:
How to programmatically take a screenshot in Android?