在一个 android 应用程序中,我试图截取一个名为 Sierpinski Triangle 的视图。但是,位图总是返回 null。谢尔宾斯基三角形只有 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);
请帮忙,我已经做了几个小时了。
这是谢尔宾斯基三角形的代码:
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);
}
}
}