Does anyone have an idea what would cause the below error?
queueBuffer: error queuing buffer to SurfaceTexture, -32
I'm using SurfaceTexture in my app. The above error occurs when I try to set as
a livewallpaper
Below is the code:
public class ClockWallpaperService extends WallpaperService {
private WallpaperEngine myEngine;
public void onCreate() {
super.onCreate();
}
#Override
public Engine onCreateEngine() {
System.out.println("Service: onCreateEngine");
this.myEngine = new WallpaperEngine();
return myEngine;
}
public void onDestroy() {
this.myEngine = null;
super.onDestroy();
}
private class WallpaperEngine extends Engine implements OnGestureListener,
OnSharedPreferenceChangeListener {
public Bitmap image1, backgroundImage;
private ArrayList<Leaf> leafList;
private Bitmap bitmap1;
private Bitmap bitmap2;
private Bitmap bitmap3;
private Bitmap currentBackgroundBitmap;
private Paint paint;
private int count;
private int heightOfCanvas;
private int widthOfCanvas;
private float touchX;
private float touchY;
private int interval;
private int amount;
private boolean fallingDown;
private float bgX = 0;
private String colorFlag;
private String backgroundFlag;
private Random rand;
private GestureDetector detector;
private static final int DRAW_MSG = 0;
private static final int MAX_SIZE = 101;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case DRAW_MSG:
drawPaper();
break;
}
}
};
/** hands colors for hour, min, sec */
private int[] colors = { 0xFFFF0000, 0xFF0000FF, 0xFFA2BC13 };
// private int bgColor;
private int width;
private int height;
private boolean visible = true;
private boolean displayHandSec;
private AnalogClock clock;
private SharedPreferences prefs;
WallpaperEngine() {
// get the fish and background image references
backgroundImage = BitmapFactory.decodeResource(getResources(),
R.drawable.bg1);
SharedPreferences sp = getSharedPreferences("back_position",
Activity.MODE_PRIVATE);
int position = sp.getInt("back_position", 1);
Global.backgroundDial = BitmapFactory.decodeResource(
getResources(), Global.BackgroundId[position]);
prefs = PreferenceManager
.getDefaultSharedPreferences(ClockWallpaperService.this);
prefs.registerOnSharedPreferenceChangeListener(this);
displayHandSec = prefs.getBoolean(
SettingsActivity.DISPLAY_HAND_SEC_KEY, true);
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
// bgColor = Color.parseColor("#C0C0C0");
clock = new AnalogClock(getApplicationContext());
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
// TODO Auto-generated method stub
super.onCreate(surfaceHolder);
System.out.println("Engine: onCreate");
this.leafList = new ArrayList<Leaf>();
this.bitmap1 = BitmapFactory.decodeResource(getResources(),
R.drawable.flower1);
this.bitmap2 = BitmapFactory.decodeResource(getResources(),
R.drawable.flower2);
this.bitmap3 = BitmapFactory.decodeResource(getResources(),
R.drawable.flower3);
this.paint = new Paint();
this.paint.setAntiAlias(true);
this.count = -1;
this.rand = new Random();
this.detector = new GestureDetector(this);
this.touchX = -1.0f;
this.touchY = -1.0f;
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ClockWallpaperService.this);
pref.registerOnSharedPreferenceChangeListener(this);
String speedStr = pref.getString("leaf_falling_speed", "20");
String amountStr = pref.getString("leaf_number", "50");
this.interval = Integer.parseInt(speedStr);
this.amount = Integer.parseInt(amountStr);
this.colorFlag = pref.getString("leaf_color", "0");
this.backgroundFlag = pref.getString("paper_background", "0");
String directionFlag = pref.getString("leaf_moving_direction", "0");
if (directionFlag.equals("0")) {
this.fallingDown = true;
} else {
this.fallingDown = false;
}
this.setTouchEventsEnabled(true);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("Engine: onDestroy");
this.mHandler.removeMessages(DRAW_MSG);
PreferenceManager.getDefaultSharedPreferences(
ClockWallpaperService.this)
.unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
this.width = width;
this.height = height;
super.onSurfaceChanged(holder, format, width, height);
}
#Override
public void onSurfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
super.onSurfaceCreated(holder);
System.out.println("Engine: onSurfaceCreate");
Canvas canvas = holder.lockCanvas();
this.heightOfCanvas = canvas.getHeight();
this.widthOfCanvas = canvas.getWidth();
System.out.println("Width = " + widthOfCanvas + ", Height = "
+ heightOfCanvas);
holder.unlockCanvasAndPost(canvas);
this.mHandler.sendEmptyMessage(DRAW_MSG);
}
#Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("Engine: onSurfaceDestroyed");
this.mHandler.removeMessages(DRAW_MSG);
if (this.currentBackgroundBitmap != null) {
this.currentBackgroundBitmap.recycle();
this.currentBackgroundBitmap = null;
}
if (this.bitmap1 != null) {
this.bitmap1.recycle();
this.bitmap1 = null;
}
if (this.bitmap2 != null) {
this.bitmap2.recycle();
this.bitmap2 = null;
}
if (this.bitmap3 != null) {
this.bitmap3.recycle();
this.bitmap3 = null;
}
super.onSurfaceDestroyed(holder);
}
#Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xOffsetStep, float yOffsetStep, int xPixelOffset,
int yPixelOffset) {
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep,
xPixelOffset, yPixelOffset);
System.out.println("xPixelOffset: " + xPixelOffset
+ ", yPixelOffset: " + yPixelOffset);
this.bgX = xPixelOffset;
}
private void drawPaper() {
count++;
if (count >= 10000) {
count = 0;
}
if (count % 10 == 0) {
if (this.leafList.size() < MAX_SIZE) {
Leaf l = null;
Bitmap temp = bitmap1;
if (colorFlag.equals("0")) {
int index = rand.nextInt(3) + 1;
switch (index) {
case 1:
temp = bitmap1;
break;
case 2:
temp = bitmap2;
break;
case 3:
temp = bitmap3;
break;
default:
temp = bitmap1;
break;
}
} else if (colorFlag.equals("1")) {
temp = bitmap1;
} else if (colorFlag.equals("2")) {
temp = bitmap2;
} else if (colorFlag.equals("3")) {
temp = bitmap3;
}
l = new Leaf(temp, this.heightOfCanvas, this.widthOfCanvas);
this.leafList.add(l);
}
}
SurfaceHolder holder = this.getSurfaceHolder();
Canvas canvas = holder.lockCanvas();
drawBackground(canvas);
int size = Math.min(this.amount, this.leafList.size());
for (int i = 0; i < size; i++) {
Leaf l = this.leafList.get(i);
if (l.isTouched()) {
l.handleTouched(touchX, touchY);
} else {
l.handleFalling(this.fallingDown);
}
l.drawLeaf(canvas, paint);
}
holder.unlockCanvasAndPost(canvas);
this.mHandler.sendEmptyMessageDelayed(DRAW_MSG, this.interval);
}
private void drawBackground(Canvas c) {
c.drawBitmap(backgroundImage, 0, 0, null);
clock.config(width / 2, height / 2, (int) (width * 0.6f),
new Date(), paint, colors, displayHandSec);
clock.draw(c);
}
#Override
public void onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
this.detector.onTouchEvent(event);
}
public boolean onDown(MotionEvent e) {
touchX = e.getX();
touchY = e.getY();
int size = Math.min(this.amount, this.leafList.size());
for (int i = 0; i < size; i++) {
Leaf l = this.leafList.get(i);
float centerX = l.getX() + l.getBitmap().getWidth() / 2.0f;
float centerY = l.getY() + l.getBitmap().getHeight() / 2.0f;
if (!l.isTouched()) {
if (Math.abs(centerX - touchX) <= 80
&& Math.abs(centerY - touchY) <= 80
&& centerX != touchX) {
l.setTouched(true);
}
}
}
return true;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}
public void onLongPress(MotionEvent e) {
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false;
}
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (key.equals("leaf_falling_speed")) {
String speedStr = sharedPreferences.getString(key, "20");
this.interval = Integer.parseInt(speedStr);
} else if (key.equals("leaf_number")) {
String amountStr = sharedPreferences.getString(key, "50");
this.amount = Integer.parseInt(amountStr);
} else if (key.equals("leaf_moving_direction")) {
String directionFlag = sharedPreferences.getString(key, "0");
if (directionFlag.equals("0")) {
this.fallingDown = true;
} else {
this.fallingDown = false;
}
} else if (key.equals("leaf_color")) {
this.colorFlag = sharedPreferences.getString(key, "0");
this.leafList.removeAll(leafList);
}
}
}
}
Related
I have canvas drawing app. I successfully done integrating floodfill algorithm for filling color for finger drawing circle and rectangle area. My problem is after filling color on finger drawing circle when i used blur mask brush effect and drawing using finger by blur mask brush then whole blur mask brush drawing is repaint again and again. Here is my code:
public class DrawingView extends View {
private final Paint mDefaultPaint;
Bitmap mBitmap;
float x, y;
ProgressDialog pd;
LinearLayout drawing_layout;
private Canvas mLayerCanvas = new Canvas();
private Bitmap mLayerBitmap;
final Point p1 = new Point();
private Stack<DrawOp> mDrawOps = new Stack<>();
private Stack<DrawOp> mUndoOps = new Stack<>();
boolean isFill = false;
private SparseArray<DrawOp> mCurrentOps = new SparseArray<>(0);
public DrawingView(Context context) {
this(context, null, 0);
}
public DrawingView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawingView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDefaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDefaultPaint.setStyle(Paint.Style.STROKE);
mDefaultPaint.setStrokeJoin(Paint.Join.ROUND);
mDefaultPaint.setStrokeCap(Paint.Cap.ROUND);
mDefaultPaint.setStrokeWidth(40);
mDefaultPaint.setColor(Color.GREEN);
setFocusable(true);
setFocusableInTouchMode(true);
setBackgroundColor(Color.WHITE);
setLayerType(LAYER_TYPE_SOFTWARE, null);
setSaveEnabled(true);
}
#Override
public boolean onTouchEvent(#NonNull MotionEvent event) {
final int pointerCount = MotionEventCompat.getPointerCount(event);
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN: {
if (isFill == true) {
int xx = (int) event.getX();
int yy = (int) event.getY();
Point pp = new Point(xx, yy);
/*Point pp = new Point();
pp.x = (int) event.getX();
pp.y = (int) event.getY();*/
final int sourceColor = mLayerBitmap.getPixel(xx, yy);
final int targetColor = mDefaultPaint.getColor();
new TheTask(mLayerBitmap, pp, sourceColor, targetColor)
.execute();
// JniBitmap.floodFill(mLayerBitmap, xx, yy, sourceColor,targetColor);
/* FloodFill f = new FloodFill();
f.floodFill(mLayerBitmap, pp, sourceColor, targetColor);*/
}
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
DrawOp current = new DrawOp(mDefaultPaint);
current.getPath().moveTo(event.getX(), event.getY());
mCurrentOps.put(id, current);
}
}
break;
case MotionEvent.ACTION_MOVE: {
if (isFill == false) {
final int id = MotionEventCompat.getPointerId(event, 0);
DrawOp current = mCurrentOps.get(id);
final int historySize = event.getHistorySize();
for (int h = 0; h < historySize; h++) {
x = event.getHistoricalX(h);
y = event.getHistoricalY(h);
current.getPath().lineTo(x, y);
}
x = MotionEventCompat.getX(event, 0);
y = MotionEventCompat.getY(event, 0);
current.getPath().lineTo(x, y);
}
}
break;
case MotionEvent.ACTION_UP: {
for (int p = 0; p < pointerCount; p++) {
final int id = MotionEventCompat.getPointerId(event, p);
mDrawOps.push(mCurrentOps.get(id));
mCurrentOps.remove(id);
}
updateLayer();
}
break;
case MotionEvent.ACTION_CANCEL: {
for (int p = 0; p < pointerCount; p++) {
mCurrentOps.remove(MotionEventCompat.getPointerId(event, p));
}
updateLayer();
}
break;
default:
return false;
}
invalidate();
return true;
}
class TheTask extends AsyncTask<Void, Integer, Void> {
Bitmap bmp;
Point pt;
int replacementColor, targetColor;
public TheTask(Bitmap bm, Point p, int sc, int tc) {
// this.bmp = bm;
mLayerBitmap = bm;
pd = new ProgressDialog(getContext());
this.pt = p;
this.replacementColor = tc;
this.targetColor = sc;
pd.setMessage("Filling....");
pd.show();
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
FloodFill f = new FloodFill();
// mLayerBitmap = f.floodFill(bmp, pt, targetColor, replacementColor);
f.floodFill(mLayerBitmap, pt, targetColor, replacementColor);
// New Commented Algorithm
// f.FloodFill(mLayerBitmap, pt, targetColor, replacementColor);
return null;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
invalidate();
isFill = false;
}
}
public void fillShapeColor(Bitmap mBitmap2) {
isFill = true;
}
public void setDrawing() {
isFill = false;
}
#Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldW, oldH);
mLayerBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mLayerCanvas.setBitmap(mLayerBitmap);
updateLayer();
}
private void updateLayer() {
for (DrawOp drawOp : mDrawOps) {
if (drawOp != null) {
// drawOp.draw(new Canvas(mLayerBitmap));
drawOp.draw(mLayerCanvas);
}
}
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode()) {
return;
}
canvas.drawBitmap(mLayerBitmap, 0, 0, null);
for (int i = 0; i < mCurrentOps.size(); i++) {
DrawOp current = mCurrentOps.valueAt(i);
if (current != null) {
current.draw(canvas);
}
}
}
public void operationClear() {
mDrawOps.clear();
mUndoOps.clear();
mCurrentOps.clear();
// To Clear Whole Canvas
mLayerCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
updateLayer();
}
public void operationUndo() {
if (mDrawOps.size() > 0) {
mUndoOps.push(mDrawOps.pop());
updateLayer();
}
}
public void operationRedo() {
if (mUndoOps.size() > 0) {
mDrawOps.push(mUndoOps.pop());
updateLayer();
}
}
public void setPaintStrokeWidth(float widthPx) {
mDefaultPaint.setStrokeWidth(widthPx);
}
/*public float getPaintStrokeWidth(){
return mDefaultPaint.getStrokeWidth();
}*/
public void setPaintOpacity(int percent) {
int alphaValue = (int) Math.round(percent * (255.0 / 100.0));
mDefaultPaint.setColor(combineAlpha(mDefaultPaint.getColor(),
alphaValue));
}
/*public int getPaintOpacity(){
this.setPaintOpacity(50);
return mDefaultPaint.getColor();
}*/
public void setPaintColor(String color) {
mDefaultPaint.setXfermode(null);
mDefaultPaint.setColor(combineAlpha(Color.parseColor(color),
mDefaultPaint.getAlpha()));
// mDefaultPaint.setColor(mDefaultPaint.getAlpha());
}
public void setPaintColor(int color) {
mDefaultPaint.setXfermode(null);
mDefaultPaint.setColor(combineAlpha(color, mDefaultPaint.getAlpha()));
}
// New Created
public void setEraser(int color){
// mDefaultPaint.setAlpha(0xFF);
mDefaultPaint.setColor(color);
mDefaultPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
public void setPaintMaskFilter(MaskFilter filter) {
mDefaultPaint.setMaskFilter(filter);
}
/*public MaskFilter getPaintMaskFilter(){
return mDefaultPaint.getMaskFilter();
}*/
public void setPaintShader(BitmapShader shader) {
mDefaultPaint.setShader(shader);
}
public void setPaintColorFilter(ColorFilter colorFilter) {
mDefaultPaint.setColorFilter(colorFilter);
}
private static int combineAlpha(int color, int alpha) {
return (color & 0x00FFFFFF) | ((alpha & 0xFF) << 24);
}
private static class DrawOp {
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path mPath = new Path();
public DrawOp(Paint paint) {
reset(paint);
}
void reset(Paint paint) {
mPath.reset();
update(paint);
}
void update(Paint paint) {
mPaint.set(paint);
}
void draw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
}
public Path getPath() {
return mPath;
}
}
}
After lots of research i fond my problem and getting correct it. Below is my code.
if (isFloodFill) {
if (mZoomMode) {
return false;
} else {
final Point p = new Point();
float[] mTmpPoint1 = new float[2];
mTmpPoint1[0] = event.getX() - mPanX;
mTmpPoint1[1] = event.getY() - mPanY;
mZoomMatrixInv.mapPoints(mTmpPoint1);
p.x = (int) (mTmpPoint1[0]);
p.y = (int) (mTmpPoint1[1]);
System.out.println("--plotX mTmpPoint0: touch:" + p.x);
System.out.println("--plotY mTmpPoint0: touch:" + p.y);
this.mBitmap = getBitmap();
if (this.mBitmap != null) {
if(p.x > mBitmap.getWidth() || p.y > mBitmap.getHeight())
{
return false;
}
else
{
if(p.x >= 0 && p.y >= 0)
{
this.color = this.mBitmap.getPixel(p.x, p.y);
}
else
{
return false;
}
}
}
try {
// isFilling = false;
new FloodFillAlgo().execute(p);
return false;
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to use 15 to 20 images to show on livewallpaper background one by one on a fix time ,but I am facing grow heap problem (Grow heap (frag case) to 8.987MB for 6220816-byte allocation) I have search everything but couldn't get through this
Any help pleas.
here is my code
public class LiveWallpaperService extends WallpaperService {
private float x;
private int y;
private int angle;
private int speed;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public Engine onCreateEngine() {
stopSelf();
return new MyWallpaperEngine();
}
class MyWallpaperEngine extends Engine {
private final Handler handle = new Handler();
private final Runnable drawRunner = new Runnable() {
#Override
public void run() {
draw();
}
};
private Boolean visble = true;
public Bitmap mBackgroundImage;
public String name;
int[] mImagesArray;
private int mImagesArrayIndex = 0;
MyWallpaperEngine() {
mImagesArray = new int[] { R.drawable.love_1_mini,
R.drawable.love_2_mini, R.drawable.love_3_mini,
R.drawable.love_4_mini, R.drawable.love_5_mini,
R.drawable.love_6_mini, R.drawable.love_7_mini,
R.drawable.love_8_mini, R.drawable.love_9_mini,
R.drawable.love_10_mini,
R.drawable.love_11_mini, R.drawable.love_12_mini,
R.drawable.love_13_mini, R.drawable.love_14_mini,
R.drawable.love_15_mini, R.drawable.love_16_mini,
R.drawable.love_17_mini, R.drawable.love_18_mini,
R.drawable.love_19_mini, R.drawable.love_20_mini };
if (mImagesArrayIndex == 0) {
x = -330; // initialize x position
y = 0; // initialize y position
} else {
x = -330; // initialize x position
y = 0; // initialize y position
}
}
#Override
public Bundle onCommand(String action, int x, int y, int z,
Bundle extras, boolean resultRequested) {
return super.onCommand(action, x, y, z, extras, resultRequested);
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
}
#Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xOffsetStep, float yOffsetStep, int xPixelOffset,
int yPixelOffset) {
draw();
}
#Override
public void onSurfaceCreated(SurfaceHolder holder) {
super.onSurfaceCreated(holder);
this.visble = false;
}
#Override
public void onTouchEvent(MotionEvent event) {
}
#Override
public void onVisibilityChanged(boolean visible) {
this.visble = visible;
if (visible) {
handle.post(drawRunner);
} else {
handle.removeCallbacks(drawRunner);
}
super.onVisibilityChanged(visible);
}
private void incrementCounter() {
mImagesArrayIndex++;
if (mImagesArrayIndex >= mImagesArray.length) {
mImagesArrayIndex = 0;
}
}
#SuppressWarnings("deprecation")
void draw() {
int count = mImagesArray[mImagesArrayIndex];
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
int scale = 2;
Resources res = getResources();
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inPreferredConfig = Bitmap.Config.RGB_565;
o2.inSampleSize = scale;
o2.inPurgeable = true;
o2.inInputShareable = true;
Bitmap image = BitmapFactory.decodeResource(res, count, o2);
Calendar mCalendar = Calendar.getInstance();
int h = mCalendar.get(Calendar.HOUR);
int m = mCalendar.get(Calendar.MINUTE);
int s = mCalendar.get(Calendar.SECOND);
if (s == 10) {
mImagesArrayIndex = 0;
}
try {
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
c = holder.lockCanvas();
c.drawColor(Color.RED);
if (c != null) {
int a = 0;
int counting = 0;
if (counting == a) {
a++;
counting++;
c.drawBitmap(image, x, y, paint);
int widthhhh = c.getWidth();
x = (float) (x + 10.10);
if (x > widthhhh + 400) {
image.recycle();
image = null;
incrementCounter();
}
}
paint.setColor(Color.RED);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} finally {
try {
if (c != null) {
holder.unlockCanvasAndPost(c);
}
handle.removeCallbacks(drawRunner);
if (visble) {
handle.postDelayed(drawRunner, 10);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
}
}
Bitmap image = BitmapFactory.decodeResource(getResources(), mImagesArray[mImagesArrayIndex]);
When your done with it call image.recycle() (see javadoc).
In your draw() method, you have this code:
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
int count = mImagesArray[mImagesArrayIndex];
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
int scale = 4;
Resources res = getResources();
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inPreferredConfig = Bitmap.Config.RGB_565;
o2.inSampleSize = scale;
o2.inPurgeable = true;
o2.inInputShareable = true;
image = BitmapFactory.decodeResource(res, count, o2);
Notice the first line calls BitmapFactory.decodeResource() and assigns the result to variable image and then later, the last line again calls BitmapFactory.decodeResource() and assigns the result to variable image. You never called recycle() on the first decoded image, so this is giving you a memory leak.
I would like to add zoom functionality to my scene. How would one do that?
This is my code at the moment:
private static float touchTurn = 0;
private static float touchTurnUp = 0;
private static float xpos = -1;
private static float ypos = -1;
static class ClearGLSurfaceView extends GLSurfaceView {
public ClearGLSurfaceView(Context context) {
super(myContext);
}
#Override
public boolean onTouchEvent(MotionEvent me) {
if (me.getAction() == MotionEvent.ACTION_DOWN) {
xpos = me.getX();
ypos = me.getY();
return true;
}
if (me.getAction() == MotionEvent.ACTION_UP) {
xpos = -1;
ypos = -1;
touchTurn = 0;
touchTurnUp = 0;
return true;
}
if (me.getAction() == MotionEvent.ACTION_MOVE) {
float xd = me.getX() - xpos;
float yd = me.getY() - ypos;
xpos = me.getX();
ypos = me.getY();
touchTurn = xd / 100f;
touchTurnUp = yd / 100f;
return true;
}
try {
Thread.sleep(15);
} catch (Exception e) {
// Doesn't matter here...
}
return super.onTouchEvent(me);
}
}
static class MyRenderer implements GLSurfaceView.Renderer {
private long time = System.currentTimeMillis();
public MyRenderer() {
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
if (fb != null) {
fb.dispose();
}
fb = new FrameBuffer(gl, w, h);
if (master == null) {
world = new World();
world.setAmbientLight(20, 20, 20);
sun = new Light(world);
sun.setIntensity(250, 250, 250);
try {
cube = loadModel(thingName, thingScale);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
cube.build();
world.addObject(cube);
Camera cam = world.getCamera();
cam.moveCamera(Camera.CAMERA_MOVEOUT, 50);
cam.lookAt(cube.getTransformedCenter());
SimpleVector sv = new SimpleVector();
sv.set(cube.getTransformedCenter());
sv.y -= 100;
sv.z -= 100;
sun.setPosition(sv);
MemoryHelper.compact();
if (master == null) {
Logger.log("Saving master Activity!");
// master = fr;
}
}
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
}
public void onDrawFrame(GL10 gl) {
if (touchTurn != 0) {
cube.rotateY(touchTurn);
touchTurn = 0;
}
if (touchTurnUp != 0) {
cube.rotateX(touchTurnUp);
touchTurnUp = 0;
}
fb.clear(back);
world.renderScene(fb);
world.draw(fb);
fb.display();
if (System.currentTimeMillis() - time >= 1000) {
Logger.log(fps + "fps");
fps = 0;
time = System.currentTimeMillis();
}
fps++;
}
If you need more information let me know.
You can increase/decrease camera's fov.
hi am doing one app for all devices using display metrics.. in 2.2 version,here i am using custom view for drawing function.some times its working well.i learn many times that time i am getting outof memory exception.in emulater i incresed heap size that time its working all fine.how to increse heap size in older versions,and whats i did wrong in my code i didnt understand can u any one have idea suggest me.....
public class A extends Activity {
BitmapDrawable sounddrawable,erasedrawable,backdrwable,fwddrwable,captiondrwable,strtdrwable,stpdrwable;
Bitmap soundbitmap,eraseBitmap,backbitmap,fwdbitmap,captionbitmap,strtbitmap,stpbitmap;
MyView myview;
GlobalClass global;
RelativeLayout.LayoutParams lp6;
SampleView sampleview;
ImageView img;
MediaPlayer nextsound;
boolean count=true;
MediaPlayer mediay2;
ImageView horn;
String user;
int username;
Bundle b;
RelativeLayout relativeLayout,relativeLayout1;
ImageView strtbtn,stpbtn,erase;
float screenHeight,screenWidth,screendensity;
public boolean action=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
screendensity = displaymetrics.densityDpi;
Log.i("screenHeight",""+screenHeight);
Log.i("screenWidth",""+screenWidth);
Log.i("screendensity",""+screendensity);
setContentView(R.layout.alh);
int topsampl=(int)(80*(screenHeight/600));
global=(GlobalClass)this.getApplication();
if(sampleview==null)
{
sampleview=new SampleView(this);
}
lp6 = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
sampleview.setLayoutParams(lp6);
lp6.setMargins(0,topsampl , 0, 0);
relativeLayout=(RelativeLayout)findViewById(R.id.relative);
RelativeLayout.LayoutParams layoutrel= (RelativeLayout.LayoutParams) relativeLayout.getLayoutParams();
layoutrel.height=(int)(600*(screenHeight/600));
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreateAAAAAAAAAA", "memoryClass:" + Integer.toString(memoryClass));
relativeLayout1=(RelativeLayout)findViewById(R.id.relative2);
RelativeLayout.LayoutParams layoutre2= (RelativeLayout.LayoutParams) relativeLayout1.getLayoutParams();
layoutre2.height=(int)(35*(screenHeight/600));
int left=(int)(15*(screenWidth/1024));
int top=(int)(50*(screenHeight/600));
int widthhh=(int)(80*(screenWidth/1024));
int hifhtttt=(int)(50*(screenHeight/600));
ImageView I2=new ImageView(this);
if(captiondrwable!= null) {
captionbitmap.recycle();
captiondrwable= null;
}
if(captiondrwable== null) {
captionbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.practise));
}
captiondrwable = new BitmapDrawable(captionbitmap);
I2.setBackgroundDrawable(captiondrwable);
RelativeLayout.LayoutParams rlp=new RelativeLayout.LayoutParams(widthhh,hifhtttt);
rlp.setMargins(left, top, 0, 0);
relativeLayout.addView(I2,rlp);
b =getIntent().getExtras();
user=b.getString("k1");
username=Integer.parseInt(user);
Log.i("username..........",""+username);
Log.i("user..........",""+user);
ImageView next=(ImageView)findViewById(R.id.imv1a);
if(fwddrwable!= null) {
fwdbitmap.recycle();
fwddrwable= null;
}
if(fwddrwable== null) {
fwdbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.next_5011));
}
fwddrwable = new BitmapDrawable(fwdbitmap);
next.setBackgroundDrawable(fwddrwable);
RelativeLayout.LayoutParams layoutnext= (RelativeLayout.LayoutParams) next.getLayoutParams();
layoutnext.height=(int)(35*(screenHeight/600));
layoutnext.width=(int)(50*(screenWidth/1024));
next.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.i("next","..........");
Intent i =new Intent(A.this,Smallletera.class);
i.putExtra("k1", user);
startActivity(i);
if(nextsound==null)
{
nextsound = MediaPlayer.create(getApplicationContext(),R.raw.chime_up);
}
nextsound.start();
if(nextsound!=null)
{
}
}
});
ImageView back=(ImageView)findViewById(R.id.back);
if(backdrwable!= null) {
backbitmap.recycle();
backdrwable= null;
}
if(backdrwable== null) {
backbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.back1_50));
}
backdrwable = new BitmapDrawable(backbitmap);
back.setBackgroundDrawable(backdrwable);
RelativeLayout.LayoutParams layoutback= (RelativeLayout.LayoutParams) back.getLayoutParams();
layoutback.height=(int)(35*(screenHeight/600));
layoutback.width=(int)(50*(screenWidth/1024));
back.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.i("next","..........");
Intent i =new Intent(A.this,HWindex.class);
startActivity(i);
}
});
if(myview==null)
{
myview = new MyView(this);
}
myview.setBackgroundColor(Color.WHITE);
myview.setId(004);
lp6 = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
myview.setLayoutParams(lp6);
lp6.setMargins(0,top , 0, 0);
relativeLayout.addView(myview,lp6);
horn=new ImageView(this);
if(sounddrawable!= null) {
soundbitmap.recycle();
sounddrawable= null;
}
if(sounddrawable== null) {
soundbitmap=BitmapFactory.decodeStream(getResources().openRawResource( R.drawable.horn));
}
sounddrawable = new BitmapDrawable(soundbitmap);
horn.setBackgroundDrawable(sounddrawable);
int left1=(int)(830*(screenWidth/1024));
int top1=(int)(50*(screenHeight/600));
int widthhh1=(int)(60*(screenWidth/1024));
int hifhtttt1=(int)(60*(screenHeight/600));
RelativeLayout.LayoutParams hn=new RelativeLayout.LayoutParams(widthhh1,hifhtttt1);
hn.setMargins(left1,top1,0,0);
relativeLayout.addView(horn,hn);
horn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediay2==null)
{
mediay2 = MediaPlayer.create(A.this, R.raw.uppercaseinstructions);
}
mediay2.start();
if(mediay2!=null)
{
}
}
});
strtbtn = new ImageView(this);
if(strtdrwable!= null) {
strtbitmap.recycle();
strtdrwable= null;
}
if(strtdrwable== null) {
strtbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.play_50));
}
strtdrwable = new BitmapDrawable(strtbitmap);
strtbtn.setBackgroundDrawable(strtdrwable);
int left2=(int)(520*(screenWidth/1024));
int top2=(int)(60*(screenHeight/600));
int widthhh2=(int)(40*(screenWidth/1024));
int hifhtttt2=(int)(40*(screenHeight/600));
strtbtn.setId(1);
RelativeLayout.LayoutParams rlp1=new RelativeLayout.LayoutParams(widthhh2,hifhtttt2);
rlp1.setMargins(left2, top2, 0, 0);
relativeLayout.addView(strtbtn,rlp1);
strtbtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count==true)
{
Log.i("---------dfgdf-----","--------");
relativeLayout.addView(sampleview,lp6);
count=false;
}
}
});
stpbtn=new ImageView(this);
if(stpdrwable!= null) {
stpbitmap.recycle();
stpdrwable= null;
}
if(stpdrwable== null) {
stpbitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.stop_50));
}
stpdrwable = new BitmapDrawable(stpbitmap);
stpbtn.setBackgroundDrawable(stpdrwable);
int left3=(int)(570*(screenWidth/1024));
int top3=(int)(60*(screenHeight/600));
stpbtn.setId(2);
RelativeLayout.LayoutParams rlp2=new RelativeLayout.LayoutParams(widthhh2,hifhtttt2);
rlp2.setMargins(left3, top3,0,0);
relativeLayout.addView(stpbtn,rlp2);
stpbtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count==false)
{
Log.i("------stop--------","--");
relativeLayout.removeView(sampleview);
count=true;
}
}
});
erase=new ImageView(this);
if(erasedrawable!= null) {
eraseBitmap.recycle();
erasedrawable= null;
}
if(erasedrawable== null) {
eraseBitmap=BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.eraser_50));
}
erasedrawable = new BitmapDrawable(eraseBitmap);
erase.setBackgroundDrawable(erasedrawable);
int left4=(int)(620*(screenWidth/1024));
int top4=(int)(50*(screenHeight/600));
int widthhh4=(int)(60*(screenWidth/1024));
int hifhtttt4=(int)(60*(screenHeight/600));
RelativeLayout.LayoutParams rlp4=new RelativeLayout.LayoutParams(widthhh4,hifhtttt4);
rlp4.setMargins(left4, top4, 0, 0);
relativeLayout.addView(erase,rlp4);
erase.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
mBitmap.eraseColor(android.graphics.Color.TRANSPARENT);
Canvas Canvas=new Canvas(mBitmap);
action=true;
myview.onDraw(Canvas);
}catch(IllegalStateException ie){
ie.printStackTrace();
}
}
}) ;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
}
private Paint mPaint;
public void colorChanged(int color) {
mPaint.setColor(color);
}
private Bitmap mBitmap;
public class MyView extends View
{
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mBitmap != null) {
mBitmap.recycle();
mBitmap=null;
}
if(mBitmap==null)
{
mBitmap= Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
}
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
Paint painto = new Paint();
painto.setAntiAlias(true);
painto.setColor(getResources().getColor(R.color.magnata));
painto.setStrokeWidth(3);
painto.setStyle(Paint.Style.FILL);
int leftx1=(int)(15*(screenWidth/1024));
int leftx2=(int)(1010*(screenWidth/1024));
int topy1=(int)(60*(screenHeight/600));
int topy2=(int)(530*(screenHeight/600));
canvas.drawLine(leftx1, topy1, leftx2, topy1, painto);
canvas.drawLine(leftx1, topy1, leftx1, topy2, painto);
canvas.drawLine(15, topy2, leftx2, topy2, painto);
canvas.drawLine(leftx2, topy1, leftx2, topy2, painto);
Paint paint1 = new Paint();
paint1.setAntiAlias(true);
paint1.setColor(Color.BLACK);
paint1.setStrokeWidth(3);
paint1.setStyle(Paint.Style.FILL);
paint1.setTextSize(15);
canvas.drawText("Practice writing the letter by tracing it over and over again . ", 110, 40, paint1);
Paint p1=new Paint();
p1.setColor(getResources().getColor(R.color.bcolor));
if(screendensity==160)
{
p1.setTextSize(630);
}
if(screendensity==240)
{
p1.setTextSize(650);
}
p1.setAntiAlias(true);
Typeface font = Typeface.createFromAsset(getAssets(), "font/KINDTRG.TTF");
p1.setTypeface(font);
float lefta=(int)(270*(screenWidth/1024));
float lefta1=(int)(290*(screenWidth/1024));
float lefta2=(int)(320*(screenWidth/1024));
float lefta3=(int)(340*(screenWidth/1024));
float lefta4=(int)(350*(screenWidth/1024));
float lefta5=(int)(370*(screenWidth/1024));
float lefta6=(int)(335*(screenWidth/1024));
float lefta7=(int)(300*(screenWidth/1024));
float lefta8=(int)(265*(screenWidth/1024));
float topa=(int)(505*(screenHeight/600));
float topa1=(int)(520*(screenHeight/600));
float topa2=(int)(510*(screenHeight/600));
float topa3=(int)(500*(screenHeight/600));
float topa4=(int)(495*(screenHeight/600));
float topa5=(int)(490*(screenHeight/600));
if(username==1)
{
canvas.drawText("A", lefta, topa, p1);
}
if(username==2)
{
canvas.drawText("B", lefta, topa, p1);
}
if(username==3)
{
canvas.drawText("C", lefta, topa, p1);
}
if(username==4)
{
canvas.drawText("D", lefta, topa1, p1);
}
if(username==5)
{
canvas.drawText("E", lefta3, topa1, p1);
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
if(action)
{
invalidate();
}
} private float mX, mY;
private float TOUCH_TOLERANCE = 2;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
public void clearAllResources() {
// Set related variables null
System.gc();
Runtime.getRuntime().gc();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
protected void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.relative));
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
protected void onstop() {
clearAllResources();
super.onStop();
}
class SampleView extends View {
java.io.InputStream is;
private Movie mMovie;
private long mMovieStart;
private byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (java.io.IOException e) {
}
return os.toByteArray();
}
public SampleView(Context context) {
super(context);
setFocusable(true);
if(global.bugcount==1)
{
is = context.getResources().openRawResource(R.drawable.a);
}
if(global.bugcount==2)
{
is = context.getResources().openRawResource(R.drawable.b);
}
if(global.bugcount==3)
{
is = context.getResources().openRawResource(R.drawable.c);
}
if(global.bugcount==4)
{
is = context.getResources().openRawResource(R.drawable.d);
}
if(global.bugcount==5)
{
is = context.getResources().openRawResource(R.drawable.e);
}
if (true) {
mMovie = Movie.decodeStream(is);
} else {
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
}
#Override protected void onDraw(Canvas canvas) {
Paint p = new Paint();
p.setAntiAlias(true);
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int)((now - mMovieStart) % dur);
mMovie.setTime(relTime);
mMovie.draw(canvas, getWidth() - mMovie.width(),
getHeight() - mMovie.height());
invalidate();
}
}
}
#Override
protected void onPause() {
if (mediay2 != null){
mediay2.stop();
mediay2.release();
mediay2=null;
}
if(nextsound != null) {
if (nextsound.isPlaying()) {
nextsound.stop();
}
nextsound.release();
nextsound = null;
}
clearAllResources();
super.onPause();
}
}
i am getting exception in inside myview on sizechnage()....
try to load your images configuring and using BitmapsOptions
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
I had tried alot & even search alot but i didn't found
the solution about the black screen
which i get by fetching the cache view on the surface view..
if is there any other way to capture the screen then let me know about this..
if i use another control & fetching the drawable cache of that control it also return null..
this is the code which i used to fetch the screen Image....
try {
// Button btn = new Button(mActivity.getApplicationContext());
view.buildDrawingCache();
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
b.compress(CompressFormat.JPEG, 100, new FileOutputStream(
"/mnt/sdcard/documents/" + new Date().getTime() + ".JPEG"));
} catch (Exception e) {
e.printStackTrace();
}
i had used this on the touch_up action of the surface view.....
EDIT:
public class DroidReaderActivity extends Activity {
private static final boolean LOG = false;
private static final int REQUEST_CODE_PICK_FILE = 1;
private static final int REQUEST_CODE_OPTION_DIALOG = 2;
private static final int DIALOG_GET_PASSWORD = 1;
private static final int DIALOG_ABOUT = 2;
private static final int DIALOG_GOTO_PAGE = 3;
private static final int DIALOG_WELCOME = 4;
private static final int DIALOG_ENTER_ZOOM = 5;
private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted";
private static final String PREFERENCES_EULA = "eula";
protected DroidReaderView mReaderView = null;
protected DroidReaderDocument mDocument = null;
protected Menu m_ZoomMenu;
FrameLayout fl;
private String mFilename;
private String mTemporaryFilename;
private String mPassword;
private int mPageNo;
private SQLiteDatabase db;
static DatabaseConnectionAPI db_api;
private boolean mDocumentIsOpen = false;
private boolean mLoadedDocument = false;
private boolean mWelcomeShown = false;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && data != null) {
// Theoretically there could be a case where OnCreate() is called
// again with the intent that was originally used to open the app,
// which would revert to a previous document. Use setIntent
// to update the intent that will be supplied back to OnCreate().
setIntent(data);
mTemporaryFilename = data.getDataString();
if (mTemporaryFilename != null) {
if (mTemporaryFilename.startsWith("file://")) {
mTemporaryFilename = mTemporaryFilename.substring(7);
}
mPassword = "";
openDocumentWithDecodeAndLookup();
}
}
break;
case REQUEST_CODE_OPTION_DIALOG:
readPreferences();
tryLoadLastFile();
break;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("ONCREATE");
db_api = new DatabaseConnectionAPI(this);
try {
db_api.createDataBase();
db_api.openDataBase();
} catch (IOException e) {
e.printStackTrace();
}
// first, show the welcome if it hasn't been shown already:
final SharedPreferences preferences = getSharedPreferences(PREFERENCES_EULA, Context.MODE_PRIVATE);
if (!preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) {
mWelcomeShown = true;
preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit();
showDialog(DIALOG_WELCOME);
}
if (mDocument == null)
mDocument = new DroidReaderDocument();
// Initialize the PdfRender engine
PdfRender.setFontProvider(new DroidReaderFontProvider(this));
// then build our layout. it's so simple that we don't use
// XML for now.
fl = new FrameLayout(this);
mReaderView = new DroidReaderView(this, null, mDocument);
// add the viewing area and the navigation
fl.addView(mReaderView);
setContentView(fl);
readPreferences();
if (savedInstanceState != null) {
mFilename = savedInstanceState.getString("filename");
if ((new File(mFilename)).exists()) {
mPassword = savedInstanceState.getString("password");
mDocument.mZoom = savedInstanceState.getFloat("zoom");
mDocument.mRotation = savedInstanceState.getInt("rotation");
mPageNo = savedInstanceState.getInt("page");
mDocument.mMarginOffsetX = savedInstanceState.getInt("marginOffsetX");
mDocument.mMarginOffsetY = savedInstanceState.getInt("marginOffsetY");
mDocument.mContentFitMode = savedInstanceState.getInt("contentFitMode");
openDocument();
mLoadedDocument = true;
}
savedInstanceState.clear();
}
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
try {
Bitmap saveBitmap = Bitmap.createBitmap(fl.getWidth(), fl.getHeight(), Bitmap.Config.ARGB_8888);
saveBitmap.compress(CompressFormat.JPEG, 100,
new FileOutputStream("/mnt/sdcard/documents/" + new Date().getTime() + ".JPEG"));
} catch (Exception e) {
e.printStackTrace();
}
}
}, 4000);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if ((mDocument != null) && mDocument.isPageLoaded()) {
outState.putFloat("zoom", mDocument.mZoom);
outState.putInt("rotation", mDocument.mRotation);
outState.putInt("page", mDocument.mPage.no);
outState.putInt("offsetX", mDocument.mOffsetX);
outState.putInt("offsetY", mDocument.mOffsetY);
outState.putInt("marginOffsetX", mDocument.mMarginOffsetX);
outState.putInt("marginOffsetY", mDocument.mMarginOffsetY);
outState.putInt("contentFitMode", mDocument.mContentFitMode);
outState.putString("password", mPassword);
outState.putString("filename", mFilename);
mDocument.closeDocument();
}
}
public void onTap(float X, float Y) {
float left, right, top, bottom;
float width = mDocument.mDisplaySizeX;
float height = mDocument.mDisplaySizeY;
boolean prev = false;
boolean next = false;
if (mDocumentIsOpen) {
left = width * (float) 0.25;
right = width * (float) 0.75;
top = height * (float) 0.25;
bottom = height * (float) 0.75;
if ((X < left) && (Y < top))
prev = true;
if ((X < left) && (Y > bottom))
next = true;
if ((X > right) && (Y < top))
prev = true;
if ((X > right) && (Y > bottom))
next = true;
if ((X > left) && (X < right) && (Y > bottom)) {
Log.d("DroidReaderMetrics", String.format("Zoom = %5.2f%%", mDocument.mZoom * 100.0));
Log.d("DroidReaderMetrics", String.format("Page size = (%2.0f,%2.0f)", mDocument.mPage.mMediabox[2]
- mDocument.mPage.mMediabox[0], mDocument.mPage.mMediabox[3] - mDocument.mPage.mMediabox[1]));
Log.d("DroidReaderMetrics", String.format(
"Display size = (%d,%d)", mDocument.mDisplaySizeX, mDocument.mDisplaySizeY));
Log.d("DroidReaderMetrics", String.format("DPI = (%d, %d)", mDocument.mDpiX, mDocument.mDpiY));
Log.d("DroidReaderMetrics", String.format("Content size = (%2.0f,%2.0f)",
mDocument.mPage.mContentbox[2] - mDocument.mPage.mContentbox[0],
mDocument.mPage.mContentbox[3] - mDocument.mPage.mContentbox[1]));
Log.d("DroidReaderMetrics", String.format("Content offset = (%2.0f,%2.0f)",
mDocument.mPage.mContentbox[0], mDocument.mPage.mContentbox[1]));
Log.d("DroidReaderMetrics", String.format(
"Document offset = (%d,%d)", mDocument.mOffsetX, mDocument.mOffsetY));
}
if (next) {
if (mDocument.havePage(1, true))
openPage(1, true);
} else if (prev) {
if (mDocument.havePage(-1, true))
openPage(-1, true);
}
}
}
protected void openDocument() {
// Store the view details for the previous document and close it.
if (mDocumentIsOpen) {
mDocument.closeDocument();
mDocumentIsOpen = false;
}
try {
this.setTitle(mFilename);
mDocument.open(mFilename, mPassword, mPageNo);
openPage(0, true);
mDocumentIsOpen = true;
} catch (PasswordNeededException e) {
showDialog(DIALOG_GET_PASSWORD);
} catch (WrongPasswordException e) {
Toast.makeText(this, R.string.error_wrong_password, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, R.string.error_opening_document, Toast.LENGTH_LONG).show();
}
}
protected void openDocumentWithDecodeAndLookup() {
try {
mTemporaryFilename = URLDecoder.decode(mTemporaryFilename, "utf-8");
// Do some sanity checks on the supplied filename.
File f = new File(mTemporaryFilename);
if ((f.exists()) && (f.isFile()) && (f.canRead())) {
mFilename = mTemporaryFilename;
openDocumentWithLookup();
} else {
Toast.makeText(this, R.string.error_file_open_failed, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, R.string.error_opening_document, Toast.LENGTH_LONG).show();
}
}
protected void openDocumentWithLookup() {
readOrWriteDB(false);
openDocument();
}
protected void openPage(int no, boolean isRelative) {
try {
if (!(no == 0 && isRelative))
mDocument.openPage(no, isRelative);
this.setTitle(new File(mFilename).getName()
+ String.format(" (%d/%d)", mDocument.mPage.no, mDocument.mDocument.pagecount));
mPageNo = mDocument.mPage.no;
} catch (PageLoadException e) {
}
}
private void readPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (prefs.getString("zoom_type", "0").equals("0")) {
float zoom = Float.parseFloat(prefs.getString("zoom_percent", "50"));
if ((1 <= zoom) && (1000 >= zoom)) {
mDocument.setZoom(zoom / 100, false);
}
} else {
mDocument.setZoom(Float.parseFloat(prefs.getString("zoom_type", "0")), false);
}
if (prefs.getBoolean("dpi_auto", true)) {
// read the display's DPI
mDocument.setDpi((int) metrics.xdpi, (int) metrics.ydpi);
} else {
int dpi = Integer.parseInt(prefs.getString("dpi_manual", "160"));
if ((dpi < 1) || (dpi > 4096))
dpi = 160; // sanity check fallback
mDocument.setDpi(dpi, dpi);
}
if (prefs.getBoolean("tilesize_by_factor", true)) {
// set the tile size for rendering by factor
Float factor = Float.parseFloat(prefs.getString("tilesize_factor", "1.5"));
mDocument.setTileMax((int) (metrics.widthPixels * factor), (int) (metrics.heightPixels * factor));
} else {
int tilesize_x = Integer.parseInt(prefs.getString("tilesize_x", "640"));
int tilesize_y = Integer.parseInt(prefs.getString("tilesize_x", "480"));
if (metrics.widthPixels < metrics.heightPixels) {
mDocument.setTileMax(tilesize_x, tilesize_y);
} else {
mDocument.setTileMax(tilesize_y, tilesize_x);
}
}
boolean invert = prefs.getBoolean("invert_display", false);
mDocument.setDisplayInvert(invert);
mReaderView.setDisplayInvert(invert);
if (prefs.getBoolean("full_screen", false)) {
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
mDocument.mHorizontalScrollLock = prefs.getBoolean("horizontal_scroll_lock", false);
}
protected void setZoom(float newZoom) {
newZoom = newZoom / (float) 100.0;
if (newZoom > 16.0)
newZoom = (float) 16.0;
if (newZoom < 0.0625)
newZoom = (float) 0.0625;
mDocument.setZoom(newZoom, false);
}
protected void tryLoadLastFile() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mFilename = prefs.getString("last_open_file", "");
if (mFilename != null) {
if ((mFilename.length() > 0) && ((new File(mFilename)).exists())) {
// Don't URL-decode the filename, as that's presumably already been done.
mPassword = "";
openDocumentWithLookup();
mLoadedDocument = true;
}
}
}
}
DroidReaderView:
public class DroidReaderView extends SurfaceView implements OnGestureListener,
SurfaceHolder.Callback, DroidReaderDocument.RenderListener {
public static Path mPath = new Path();
private static StringBuffer sbx = new StringBuffer();
private static StringBuffer sby = new StringBuffer();
public static Paint mPaint = new Paint();
public static Paint nullpaint = new Paint();
private String sx, sy, sbx_str, sby_str;
public static Canvas mCanvas = new Canvas();
private int pid = 1;
/**
* Debug helper
*/
protected final static String TAG = "DroidReaderView";
protected final static boolean LOG = false;
/**
* our view thread which does the drawing
*/
public DroidReaderViewThread mThread;
/**
* our gesture detector
*/
protected final GestureDetector mGestureDetector;
/**
* our context
*/
protected final DroidReaderActivity mActivity;
/**
* our SurfaceHolder
*/
protected final SurfaceHolder mSurfaceHolder;
public static DroidReaderDocument mDocument;
protected boolean mDisplayInvert;
/**
* constructs a new View
*
* #param context
* Context for the View
* #param attrs
* attributes (may be null)
*/
public DroidReaderView(final DroidReaderActivity activity, AttributeSet attrs, DroidReaderDocument document) {
super(activity, attrs);
mActivity = activity;
mSurfaceHolder = getHolder();
mDocument = document;
mDocument.mRenderListener = this;
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
// tell the SurfaceHolder to inform this thread on
// changes to the surface
mSurfaceHolder.addCallback(this);
mGestureDetector = new GestureDetector(this);
}
/* event listeners: */
#Override
protected void onDraw(Canvas canvas) {
mThread.c = canvas;
mThread.c = mSurfaceHolder.lockCanvas();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
mThread.c.drawPath(mPath, mPaint);
mSurfaceHolder.unlockCanvasAndPost(mThread.c);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (LOG)
Log.d(TAG, "onFling(): notifying ViewThread");
mThread.mScroller.fling(0, 0, -(int) velocityX, -(int) velocityY, -4096, 4096, -4096, 4096);
mThread.triggerRepaint();
return true;
}
/* keyboard events: */
#Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
if (LOG)
Log.d(TAG, "onKeyDown(), keycode " + keyCode);
return false;
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent msg) {
if (LOG)
Log.d(TAG, "onKeyUp(), keycode " + keyCode);
return false;
}
/* interface for the GestureListener: */
#Override
public void onLongPress(MotionEvent e) {
if (LOG)
Log.d(TAG, "onLongPress(): ignoring!");
}
#Override
public void onNewRenderedPixmap() {
if (LOG)
Log.d(TAG, "new rendered pixmap was signalled");
mThread.triggerRepaint();
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (LOG)
Log.d(TAG, "onScroll(), distance vector: " + distanceX + "," + distanceY);
mDocument.offset((int) distanceX, (int) distanceY, true);
mThread.triggerRepaint();
return true;
}
#Override
public void onShowPress(MotionEvent e) {
if (LOG)
Log.d(TAG, "onShowPress(): ignoring!");
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// Pass the tap, and the window dimensions, to the activity to process.
mActivity.onTap(e.getX(), e.getY());
return true;
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.moveTo(x, y);
mX = x;
sx = Float.toString(mX);
sbx.append(sx);
sbx.append(",");
mY = y;
sy = Float.toString(mY);
sby.append(sy);
sby.append(",");
sbx_str = sbx.toString();
sby_str = sby.toString();
}
private void draw_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
sx = Float.toString(mX);
sbx.append(sx);
sbx.append(",");
mY = y;
sy = Float.toString(mY);
sby.append(sy);
sby.append(",");
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
sx = Float.toString(mX);
sbx.append(sx);
sbx.append(",");
sy = Float.toString(mY);
sby.append(sy);
sby.append(",");
mPath.reset();
sbx_str = sbx.toString().trim();
sby_str = sby.toString().trim();
insert(TAGS.presentation_id, mDocument.mPage.no, sbx_str, sby_str);
sbx = new StringBuffer();
sby = new StringBuffer();
System.out.println(sbx_str.trim());
System.out.println(sby_str.trim());
}
#Override
public boolean onTouchEvent(final MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
draw_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
try {
// Button btn = new Button(mActivity.getApplicationContext());
// buildDrawingCache();
// setDrawingCacheEnabled(true);
// Bitmap b = getDrawingCache();
// b.compress(CompressFormat.JPEG, 100, new FileOutputStream(
// "/mnt/sdcard/documents/" + new Date().getTime() + ".JPEG"));
} catch (Exception e) {
e.printStackTrace();
}
break;
}
invalidate();
if (LOG) {
Log.d(TAG, "onTouchEvent(): notifying mGestureDetector");
invalidate();
}
if (mGestureDetector.onTouchEvent(event)) {
invalidate();
return true;
}
return true;
}
#Override
public boolean onTrackballEvent(MotionEvent event) {
if (LOG)
Log.d(TAG, "onTouchEvent(): notifying ViewThread");
mDocument
.offset((int) event.getX() * 20, (int) event.getY() * 20, true);
mThread.triggerRepaint();
return true;
}
/* surface events: */
public void setDisplayInvert(boolean invert) {
if (mThread != null)
mThread.setPainters(invert);
mDisplayInvert = invert;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (LOG)
Log.d(TAG, "surfaceChanged(): size " + width + "x" + height);
mDocument.startRendering(width, height);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (LOG)
Log.d(TAG, "surfaceCreated(): starting ViewThread");
mThread = new DroidReaderViewThread(holder, mActivity, mDocument);
mThread.setPainters(mDisplayInvert);
mThread.start();
}
/* render events */
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (LOG)
Log.d(TAG, "surfaceDestroyed(): dying");
mDocument.stopRendering();
boolean retry = true;
mThread.mRun = false;
mThread.interrupt();
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public boolean onDown(MotionEvent e) {
return false;
}
DroidReaderViewThread :
Thread that cares for blitting Pixmaps onto the Canvas and handles scrolling
class DroidReaderViewThread extends Thread {
public Canvas c = new Canvas();
private Cursor mCursor;
private Path mPath1 = new Path();
private StringBuffer sbx_read, sby_read;
public static Paint mPaint2 = new Paint();
public static Paint mPaint3 = new Paint();
Path old_path = new Path();
/**
* Debug helper
*/
protected final static String TAG = "DroidReaderViewThread";
protected final static boolean LOG = false;
/**
* the SurfaceHolder for our Surface
*/
protected final SurfaceHolder mSurfaceHolder;
/**
* Paint for not (yet) rendered parts of the page
*/
protected final Paint mEmptyPaint;
/**
* Paint for filling the display when there is no PdfPage (yet)
*/
protected final Paint mNoPagePaint;
/**
* Paint for the status text
*/
protected final Paint mStatusPaint;
/**
* Flag that our thread should be running
*/
protected boolean mRun = true;
/**
* our scroller
*/
protected final Scroller mScroller;
protected final DroidReaderDocument mDocument;
/**
* Background render thread, using the SurfaceView programming scheme
*
* #param holder
* our SurfaceHolder
* #param context
* the Context for our drawing
*/
public DroidReaderViewThread(SurfaceHolder holder, Context context, DroidReaderDocument document) {
// store a reference to our SurfaceHolder
mSurfaceHolder = holder;
mDocument = document;
// initialize Paints for non-Pixmap areas
mEmptyPaint = new Paint();
mNoPagePaint = new Paint();
mStatusPaint = new Paint();
setPainters(false);
// the scroller, i.e. the object that calculates/interpolates
// positions for scrolling/jumping/flinging
mScroller = new Scroller(context);
}
/**
* ll this does the actual drawing to the Canvas for our surface
*/
private void doDraw() {
if (LOG)
Log.d(TAG, "drawing...");
c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
if (!mDocument.isPageLoaded()) {
// no page/document loaded
if (LOG)
Log.d(TAG, "no page loaded.");
c.drawRect(0, 0, c.getWidth(), c.getHeight(), mNoPagePaint);
} else if (mDocument.havePixmap()) {
// we have both page and Pixmap, so draw:
// background:
if (LOG)
Log.d(TAG, "page loaded, rendering pixmap");
c.drawRect(0, 0, c.getWidth(), c.getHeight(), mEmptyPaint);
Log.d("CALL", "CALL");
c.drawBitmap(mDocument.mView.mBuf, 0,
mDocument.mView.mViewBox.width(), -mDocument.mOffsetX + mDocument.mView.mViewBox.left,
-mDocument.mOffsetY + mDocument.mView.mViewBox.top,
mDocument.mView.mViewBox.width(), mDocument.mView.mViewBox.height(), false, null);
try {
Log.d("Reading", "Reading");
mCursor = DroidReaderActivity.db_api
.ExecuteQueryGetCursor("SELECT * FROM path WHERE page_no=" + mDocument.mPage.no
+ " AND presentation_id=" + TAGS.presentation_id + ";");
if (!mCursor.equals(null)) {
mCursor.moveToFirst();
float x1 = 0, y1 = 0;
int pid = 0;
do {
sbx_read = new StringBuffer();
sbx_read.append(mCursor.getString(mCursor.getColumnIndex("x_path")));
sby_read = new StringBuffer();
sby_read.append(mCursor.getString(mCursor.getColumnIndex("y_path")));
String[] sbx_read_array = sbx_read.toString().trim().split(",");
String[] sby_read_array = sby_read.toString().trim().split(",");
for (int i = 0; i < sbx_read_array.length; i++) {
x1 = Float.parseFloat(sbx_read_array[i].toString());
y1 = Float.parseFloat(sby_read_array[i].toString());
if (pid != mCursor.getInt(mCursor.getColumnIndex("path_id"))) {
pid = mCursor.getInt(mCursor.getColumnIndex("path_id"));
Log.d("New Path Id.",
String.valueOf(mCursor.getInt(mCursor.getColumnIndex("path_id"))));
mPath1.reset();
mPath1.moveTo(x1, y1);
} else {
Log.d("Path id repeating.",
String.valueOf(mCursor.getInt(mCursor.getColumnIndex("path_id"))));
}
mPath1.lineTo(x1, y1);
c.drawPath(mPath1, DroidReaderView.mPaint);
}
} while (mCursor.moveToNext());
mCursor.close();
Log.d("Read mode Complete", "Read mode Complete");
}
} catch (Exception e) {
// Log.d("read Cursor", e.getMessage().toString());
}
} else {
// page loaded, but no Pixmap yet
if (LOG)
Log.d(TAG, "page loaded, but no active Pixmap.");
c.drawRect(0, 0, c.getWidth(), c.getHeight(), mEmptyPaint);
mPaint3.setAntiAlias(true);
mPaint3.setDither(true);
mPaint3.setColor(Color.TRANSPARENT);
mPaint3.setStyle(Paint.Style.STROKE);
mPaint3.setStrokeJoin(Paint.Join.ROUND);
mPaint3.setStrokeCap(Paint.Cap.ROUND);
mPaint3.setStrokeWidth(12);
mPaint3.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
c.drawPath(old_path, mPaint3);
}
} finally {
if (c != null) {
mPaint2.setAntiAlias(true);
mPaint2.setDither(true);
mPaint2.setColor(Color.GREEN);
mPaint2.setStyle(Paint.Style.STROKE);
mPaint2.setStrokeJoin(Paint.Join.ROUND);
mPaint2.setStrokeCap(Paint.Cap.ROUND);
mPaint2.setStrokeWidth(12);
c.drawPath(DroidReaderView.mPath, mPaint2);
// DroidReaderView.mPath.reset();
// old_path = DroidReaderView.mPath;
}
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
/**
* Main Thread loop
*/
#SuppressWarnings("static-access")
#Override
public void run() {
while (mRun) {
boolean doSleep = true;
if (!mScroller.isFinished()) {
if (mScroller.computeScrollOffset()) {
if (LOG)
Log.d(TAG, "new scroll offset");
doSleep = false;
int oldX = mDocument.mOffsetX;
int oldY = mDocument.mOffsetY;
mDocument.offset(mScroller.getCurrX(), mScroller.getCurrY(), true);
if ((oldX == mDocument.mOffsetX) && (oldY == mDocument.mOffsetY))
mScroller.abortAnimation();
} else {
mScroller.abortAnimation();
}
}
doDraw();
// if we're allowed, we will go to sleep now
if (doSleep) {
try {
// nothing to do, wait for someone waking us up:
if (LOG)
Log.d(TAG, "ViewThread going to sleep");
// between
// the check for pending interrupts and the sleep() which
// could lead to a not-handled repaint request:
if (!this.interrupted())
Thread.sleep(3600000);
} catch (InterruptedException e) {
if (LOG)
Log.d(TAG, "ViewThread woken up");
}
}
}
// mRun is now false, so we shut down.
if (LOG)
Log.d(TAG, "shutting down");
}
public void setPainters(boolean invert) {
// initialize Paints for non-Pixmap areas
mEmptyPaint.setStyle(Paint.Style.FILL);
mNoPagePaint.setStyle(Paint.Style.FILL);
mStatusPaint.setStyle(Paint.Style.FILL);
if (invert)
mEmptyPaint.setColor(0xff000000); // black
else
mEmptyPaint.setColor(0xffc0c0c0); // light gray
if (invert)
mNoPagePaint.setColor(0xff000000); // black
else
mNoPagePaint.setColor(0xff303030); // dark gray
if (invert)
mStatusPaint.setColor(0xff000000); // black
else
mStatusPaint.setColor(0xff808080); // medium gray
}
public void triggerRepaint() {
if (LOG)
Log.d(TAG, "repaint triggered");
interrupt();
}
}
I am using this, and its works fine in my case,
Here imageFrame is FrameLayout, root view of my View which I want to save as bitmap..
Bitmap saveBitmap = Bitmap.createBitmap(imageFrame.getWidth(), imageFrame.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(saveBitmap);
imageFrame.draw(c);
Try replacing imageFrame with your view.
EDIT:
Date date = new Date();
File filename = new File(file.getAbsoluteFile(), "" + date.getTime() + ".jpg");
try
{
fOut = new FileOutputStream(filename);
saveBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
try
{
fOut.flush();
fOut.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
EDIT 2:
private void doDraw() {
int w = WIDTH_PX, h = HEIGHT_PX;
BitmapConfig conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
c = new Canvas(bmp);