Android 保存画布、绘制圆的位图
下面有一个类,它扩展了View,并重写了onDraw方法,以便在加载的位图上绘制圆环 位图加载成功并显示在屏幕上。当用户触摸屏幕时,会画一个圆圈 我有一个浮动操作按钮,可以将位图压缩为一个字节[]。然后,该字节[]被发送到另一个要显示的活动。不幸的是,生成的位图没有任何圆 canvas是onDraw中的本地对象,mCBitmap和tCanvas是全局变量,因此方法saveImage可以访问数据 谁能告诉我为什么没有一个圆被复制到生成的位图中Android 保存画布、绘制圆的位图,android,bitmap,android-canvas,Android,Bitmap,Android Canvas,下面有一个类,它扩展了View,并重写了onDraw方法,以便在加载的位图上绘制圆环 位图加载成功并显示在屏幕上。当用户触摸屏幕时,会画一个圆圈 我有一个浮动操作按钮,可以将位图压缩为一个字节[]。然后,该字节[]被发送到另一个要显示的活动。不幸的是,生成的位图没有任何圆 canvas是onDraw中的本地对象,mCBitmap和tCanvas是全局变量,因此方法saveImage可以访问数据 谁能告诉我为什么没有一个圆被复制到生成的位图中 import android.content.Cont
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import org.apache.commons.io.IOUtils;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.graphics.PointF;
/**
* Created by MatthewW on 14/06/2017.
*/
public class TouchView extends View {
private static final String TAG = TouchView.class.getSimpleName();
Bitmap bgr;
File tempFile;
private byte[] imageArray;
private Paint pTouch;
Context context;
private SparseArray<ColouredCircle> mPointers;
public int x;
public int y;
int circleCount;
int radius;
protected byte [] data;
Bitmap mCBitmap;
Canvas tCanvas;
public TouchView(Context context) {
super(context);
this.context = context;
}
public TouchView(Context context, AttributeSet attr) {
super(context,attr);
Log.e(TAG, "inside touchview constructor");
this.context = context;
radius = 70;
circleCount = 0;
copyReadAssets();
imageArray = new byte[(int)tempFile.length()];
Log.e(TAG, "imageArray has length = " + imageArray.length);
try{
InputStream is = new FileInputStream(tempFile);
BufferedInputStream bis = new BufferedInputStream(is);
DataInputStream dis = new DataInputStream(bis);
int i = 0;
while (dis.available() > 0 ) {
imageArray[i] = dis.readByte();
i++;
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length);
if(bm == null){
Log.e(TAG, "bm = null");
}else{
Log.e(TAG, "bm = not null");
}
mPointers = new SparseArray<ColouredCircle>();
bgr = bm.copy(bm.getConfig(), true);
bm.recycle();
pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
// pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
pTouch.setColor(Color.RED);
pTouch.setStyle(Paint.Style.STROKE);
pTouch.setStrokeWidth(5);
}// end of touchView constructor
private void copyReadAssets() {
AssetManager assetManager = context.getAssets();
InputStream in = null;
OutputStream out = null;
tempFile = new File(context.getFilesDir(), "bodymap.jfif");
try {
in = assetManager.open("bodymap.jfif");
out = context.openFileOutput(tempFile.getName(), Context.MODE_WORLD_READABLE);
IOUtils.copy(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
Log.e(TAG, "about to draw bgr ");
// canvas.drawBitmap(bgr, 0, 0, null);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Rect frameToDraw = new Rect(0, 0, width, height);
RectF whereToDraw = new RectF(0, 0, width, height - 300);
canvas.drawBitmap(bgr,frameToDraw,whereToDraw, null);
if(mPointers != null) {
Log.e(TAG, "mPointers.size() = " + mPointers.size());
for (int i = 0; i < mPointers.size(); i++) {
PointF p = mPointers.get(i).getPointF();
x = (int) p.x;
y = (int) p.y;
pTouch.setColor(mPointers.get(i).getColour());
canvas.drawCircle(x, y, radius, pTouch);
mCBitmap = Bitmap.createBitmap(bgr.getWidth(), bgr.getHeight(), bgr.getConfig());
tCanvas = new Canvas(mCBitmap);
tCanvas.drawBitmap(bgr, 0, 0, null);
tCanvas.drawCircle(x, y, radius, pTouch);
tCanvas.drawBitmap(mCBitmap, 0, 0, null);
}
}
}//end of onDraw
@Override
public boolean onTouchEvent(MotionEvent me) {
switch (me.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
/*int ai = me.getActionIndex();
PointF pt = new PointF(me.getX(ai), me.getY(ai));
mPointers.put(me.getPointerId(ai), pt);
Log.e(TAG, "mPointers.size() = " + mPointers.size() + "me.getPointerId(ai) = "
+ me.getPointerId(ai) + " me.getX(ai) = " + me.getX(ai) + " me.getY(ai) = " + me.getY(ai));*/
int ai = me.getActionIndex();
PointF pt = new PointF(me.getX(ai), me.getY(ai));
ColouredCircle cc = new ColouredCircle(pTouch.getColor(),pt);
mPointers.put(circleCount, cc);
circleCount++;
invalidate();
return true;
}
case MotionEvent.ACTION_UP: {
}
case MotionEvent.ACTION_POINTER_UP: {
/*int pid = me.getPointerId(me.getActionIndex());
mPointers.remove(pid);*/
return true;
}
case MotionEvent.ACTION_MOVE: {
/*for (int i = 0; i < me.getPointerCount(); ++i) {
PointF pt = mPointers.get(me.getPointerId(i));
pt.set(me.getX(i), me.getY(i));
invalidate();
}*/
return true;
}
}
return false;
}
public void showToastMessage(String mess){
Toast.makeText(TouchView.this.getContext(), mess.toString(), Toast.LENGTH_SHORT).show();
}
public int getRadius() {
return radius;
}
public void setRadius(int r) {
radius = r;
invalidate();
}
public void setCircleColour(String colourMode){
if(colourMode.equalsIgnoreCase("RED")){
pTouch.setColor(Color.RED);
}else if(colourMode.equalsIgnoreCase("BLUE")){
pTouch.setColor(Color.BLUE);
}else if(colourMode.equalsIgnoreCase("GREY")){
pTouch.setColor(Color.GRAY);
}
}
public byte[] saveImage(){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mCBitmap.compress(Bitmap.CompressFormat.JPEG, 100 /*ignored for PNG*/, bos);
data = bos.toByteArray();
try {
bos.flush();
bos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
bos.flush();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ( data == null){
Log.e(TAG, "data in touchview before save clicked is null");
}else{
Log.e(TAG, "data in touchview before saved clicked is not null and has length + " + data.length);
}
return data;
}
}//end of class
这是一张允许用户在图像上放置圆圈的活动图片。bg图像是全屏的
下面是下一个活动的输出图片,其中带圆圈的图像被转换为字节[]并显示。正如您所看到的,bg图像不是全屏的,但是卷轴处于正确的位置
在onDraw(…)
中,更改:
Rect frameToDraw = new Rect(0, 0, width, height);
致:
当您在onDraw(…)
中显示图像时,当框架调用onDraw(…)
时,您不存在此问题的一个原因可能是,如果您的目标sdk>=14(,第二段,第一句话),框架提供的Canvas
对象默认是硬件加速的
如图所示,当画布被硬件加速时,其密度似乎设置为0。但是,如果在字段TouchView\bgr
上调用Bitmap.getDensity()。这是因为位图在创建时具有当前设备屏幕的密度
接下来,您在0 ppi画布上绘制了高密度位图(在我的设备上,密度为320 ppi)-->它将被绘制得更大
但是,在saveImage中,您可以从头创建一个位图
,然后从该位图创建一个画布
,然后将该画布提供给调用绘制(…)
。您刚刚创建的这个新画布将不会被硬件加速,并且还将具有新创建位图的密度(在我的示例中为320 ppi)
当您在onDraw(…)
中绘制身体地图图像时,您将使用320dp在画布上绘制它,与您的图像相同
这仍然可以很好地工作,但是您指定要从身体图中绘制一个屏幕宽度x屏幕高度的区域,假设为1920x1080,它很可能更小,让我们假设1000x600,使用frameToDraw
在这种情况下,Android将做什么?嗯,Canvas#drawBitmap(…)
的Javadoc告诉我们:
注意:如果油漆包含生成遮罩的遮罩过滤器
超出位图的原始宽度/高度(例如。
BlurMaskFilter),则位图将被绘制为在
具有钳制模式的着色器。因此,颜色超出了原稿
宽度/高度将是复制的边缘颜色
这基本上意味着:我将使用1000x600并按照应该绘制的方式绘制像素,其余像素直到1920x1080我将使用我选择的颜色填充(可能是黑色或白色,或透明?)
现在,您可以通过whereToDraw
表示希望1920x1080区域映射到1620x1080区域。为此,android将进一步缩小位图,使bodymap
更小
最简单的解决方案是在创建frameToDraw
区域时,在onDraw(…)
中指定位图的实际尺寸
此外,如果这些代码片段正在测试代码,也可以,但在清理代码时,请确保在使用onDraw(…)
时遵循上述指导原则
最重要的一点是:
- 您真的不应该在
onDraw(…)
方法中分配对象,因为它们可能经常被调用,这将杀死您的垃圾收集器。(即frameToDraw和whereToDraw-您可以在构造函数中预先分配它们)
- 通过利用视图的图形缓存,可以更轻松地获取屏幕位图
只需将您的saveImage
更改为:
public byte[] saveImage() {
//reder the view once, in software.
buildDrawingCache();
//get the rendered bitmap
Bitmap bitmap = getDrawingCache();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 /*ignored for PNG*/, bos);
byte[] data = bos.toByteArray();
//destroy the drawing cache, to clear up the memory
destroyDrawingCache();
try {
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (data == null) {
Log.e(TAG, "data in touchview before save clicked is null");
} else {
Log.e(TAG, "data in touchview before saved clicked is not null and has length + " + data.length);
}
return data;
}
见:
希望这有帮助您好,感谢您提供如此详细的答案。我想我需要更多地阅读android图形。现在很好用!我还将进行这些更改,以将对象放置在构造函数中。再次感谢!
Rect frameToDraw = new Rect(0, 0, width, height);
Rect frameToDraw = new Rect(0, 0, bgr.getWidth(), bgr.getHeight());
public byte[] saveImage() {
//reder the view once, in software.
buildDrawingCache();
//get the rendered bitmap
Bitmap bitmap = getDrawingCache();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 /*ignored for PNG*/, bos);
byte[] data = bos.toByteArray();
//destroy the drawing cache, to clear up the memory
destroyDrawingCache();
try {
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (data == null) {
Log.e(TAG, "data in touchview before save clicked is null");
} else {
Log.e(TAG, "data in touchview before saved clicked is not null and has length + " + data.length);
}
return data;
}