gpt4 book ai didi

java - 如何从 View 的 onDraw() 方法中提取位图?

转载 作者:行者123 更新时间:2023-11-29 00:22:52 24 4
gpt4 key购买 nike

如何从 CustomView 的 onDraw() 例程中提取 Bitmap 对象?

这是我的代码:

public class DrawView extends View {
private Paint paint = new Paint();
private Point point;
private LinkedList<Point> listaPontos;
private static Context context;

class Point {

public Point(float x, float y) {
this.x = x;
this.y = y;
}

float x = 0;
float y = 0;
}

public DrawView(Context context) {
super(context);
this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
this.context = context;
paint.setColor(Color.YELLOW);
this.listaPontos = new LinkedList<Point>();
}

@Override
public void onDraw(Canvas canvas) {

if(listaPontos.size() != 0){
for(Point point : listaPontos){
canvas.drawCircle(point.x, point.y, 25, paint);
}
}
calculateAmount(canvas);
}

private void calculateAmount(Canvas canvas) {
LinkedList<Integer> colors = new LinkedList<Integer>();
for(int i = 0 ; i != canvas.getWidth(); i++)
{
for(int j = 0; j != canvas.getHeight(); j++){

int color = BITMAP.getPixel(i,j); //How can I get the bitmap generated on onDraw ?

colors.add(color);
}
}

int yellow = 0;
int white = 0;

for(Integer cor : colors) {

if(cor == Color.WHITE) {
white++;
}
if(cor == Color.YELLOW) {
yellow++;
}
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {

switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
listaPontos.add(new Point(event.getX(), event.getY()));
break;
}
invalidate();
return true;
}
}

提前致谢;)

编辑:位图是计算每个像素的颜色,如何将背景图像添加到我的 DrawView ?我测试了 this.setBackgroundResource(R.drawable.a);在构造函数中但没有工作,再次感谢 ;)

最佳答案

无法从 Canvas 中提取位图。至少不能直接提取。

但是,可以使用Canvas在位图上绘制,然后使用位图

Bitmap mDrawBitmap;
Canvas mBitmapCanvas;
Paint drawPaint = new Paint();

@Override
public void onDraw(Canvas canvas) {

drawPaint.setColor(Color.RED);

if (mDrawBitmap == null) {
mDrawBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
mBitmapCanvas = new Canvas(mDrawBitmap);
}

// clear previously drawn stuff
mBitmapCanvas.drawColor(Color.WHITE);

// draw on the btimapCanvas
mBitmapCanvas.drawStuff(...);
//... and more

// after drawing with the bitmapcanvas,
//all drawn information is stored in the Bitmap


// draw everything to the screen
canvas.drawBitmap(mDrawBitmap, 0, 0, drawPaint);
}

onDraw()方法完成后,所有绘制的信息都会被绘制到屏幕上(通过调用canvas.drawBitmap(...),同时也存储在您的 Bitmap 对象中(因为所有绘制操作都是在使用 Bitmap 创建的 Canvas 上完成的)。

关于java - 如何从 View 的 onDraw() 方法中提取位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21914978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com