I use function loadBitmap to get bitmap with canvas, but the place of the bitmap inside is wrong,I have thought for a long time, however could not find the reason. points is set in dp by layout_marignLeft and layout_marinTop in layout.xml.
Here is the code.
public Bitmap loadBitmap() {
Bitmap b = BitmapFactory.decodeResource(mContext.getResources(),bg)
.copy(Bitmap.Config.ARGB_8888, true);
if (null == ids ||null == points || ids.size() != points.size())
return b;
Canvas c = new Canvas(b);
for (int i = 0; i < ids.size(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), ids.get(i));
c.drawBitmap(bitmap, dpToPx(points.get(i).x), dpToPx(points.get(i).y), null);
bitmap.recycle();
}
c.save(Canvas.ALL_SAVE_FLAG);
c.restore();
return b;
}
public float dpToPx(float x) {
return mContext.getResources().getDisplayMetrics().density * x;
}
is the image that you are using having padding in it. If image has some extra alpha boundary then your calculations can go wrong.
The problem has nothing to do with View and Canvas,I want to the app to fullscreen, but the tablet has navigation bar, which cause the layout not fill the screen, and the params of margin_left and margin_right are totally wrong.When I hide the navigation bar,everything is ok.Here is the method to hide navigation bar.Android tablet navigation bar won't hide
Related
i want to get exacly bitmap show on screen after(scale,filtercolor,...) and work with its pixel for example in order to remove transparent pixel :
for (int y = 0; y < sourceBitmap1.getHeight(); y++)
for (int x = 0; x < sourceBitmap1.getWidth(); x++)
if (sourceBitmap1.getPixel(x, y) == Color.TRANSPARENT) {
//todo do something
}
but it is important to get bitmap related to target Imageview. as i see other post can do this with this method:
public static Bitmap loadBitmapFromView(ImageView i) {
i.setDrawingCacheEnabled(true);
i.measure(FrameLayout.MeasureSpec.makeMeasureSpec(0, FrameLayout.MeasureSpec.UNSPECIFIED),
FrameLayout.MeasureSpec.makeMeasureSpec(0, FrameLayout.MeasureSpec.UNSPECIFIED));
i.layout(0, 0, i.getMeasuredWidth(), i.getMeasuredHeight());
i.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(i.getDrawingCache(true));
i.setDrawingCacheEnabled(false);
return b;
}
but method return null , any idea?
thanks in advanced
try this to get bitmap from imageview
Bitmap bitmap = ((BitmapDrawable) imgview.getDrawable()).getBitmap();
Im extending the View class in order to have a "drawable" view witch contains the desired background.
The problem is when this class works fine in other activity (same app).
Here is the class that extends View:
public class BackgroundMap extends View {
private String strmap;
private int totalWidth;
public BackgroundMap(Context context, String map, int w, int h) {
super(context);
super.setLayoutParams(new LayoutParams(w, h));
totalWidth = w;
strmap = map;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Resources res = getResources();
int eachBoxSize = totalWidth/10;
float left = 0;
float top = 0;
Paint paint = new Paint();
for(char c : strmap.toCharArray()){
Bitmap bm = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(res, Terrain.getResource(c)), eachBoxSize, eachBoxSize, false);
canvas.drawBitmap(bm, left, top, paint);
if(left == totalWidth - eachBoxSize){
left = 0;
top += eachBoxSize;
}else{
left += eachBoxSize;
}
}
}
}
This view works like this: somelayout.addView(new BackgroundMap(arg..));
the String map argument means an array of terrains (char) ids that point to several little png images.
and this is how i use it in my Activity:
ly_rbtn_image = (FrameLayout) findViewById(R.id.ly_rbtn_image);
ly_rbtn_image.post(new Runnable() {
#Override
public void run() {
imagewidth = ly_rbtn_image.getWidth();
ly_rbtn_image.addView(new BackgroundMap(getApplicationContext(), str, imagewidth, imagewidth));
}
});
i check with logcat the width of parent layout and it has 225px. As you can see the image below only build the first row of bitmaps... but this IS NOT a loop problem
I check inside the custom view loop at onDraw method if there was a problem here but it iterate the whole string (100 chars, 10x10 bitmaps)
hope u can help me :S
http://deviantsart.com/1afcam8.png
solved. please delete me.
the bitmaps were pushed at right till the end of the loop. So in fact, i didnt know why this happened.
UNTIL I CHECKED THE BOUNDS OF THE RESULT VIEW IN LOGCAT x))) the view had 2000 pixels width and 20 height... there we go:
When i get the total width of the device, casually was a number divisible by 10 (10x10 grid) so in fact was lucky not having this problem before (building the same map in other view).
Then, the problem was the need to print the same map (or grid) in an other view, not big as the device width, so the total width (parent width) was not divisible by the number of columns of the grid (im ashamed x)).
I was a frequent guest at stackoverflow until I ran into a problem that I really couldn't find anything existing about. So here is my first question:
I am building a camera app in which the user can take several pictures before proceeding to the next step. I want to give the user the possibility to review and delete pictures while stying in the camera stage, so I have written a custom View to show Thumbnails of the already captured images with a delete button. These "Thumbviews" are contained in a LinearLayout that is located on top of the camerapreview-SurfaceView and has a default visibility of "GONE". The user can toggle the visibility with a button.
It all works fine, but I have one problem:
When I take more than about 10 pictures, I get an OutOfMemoryError. The thumbnails are really small and don't take a lot of memory and also I recycle the original Bitmaps and perform a System.gc() after creating the thumbs.
The weird thing is, when I press the button that sets the visibility of the containing LinearLayout to "VISIBLE" and again to "GONE", apparently all the memory gets freed and I can take many more pictures than 10.
I've tried switching the visibility in code but that doesn't work, and also destroying the drawing cache.
There has to be another way to free that memory besides pushing my visibility button 2 times ;-)
Here's the code for the ThumbView:
public class ThumbView extends View {
private Bitmap mBitmap;
private Bitmap mScaledBitmap;
private int mWidth, mHeight, mPosX, mPosY;
static private Bitmap mDeleteBitmap;
private File mPreviewFile;
private File mFinalFile;
private Orientation mOrientation;
private boolean mRed;
public ThumbView(Context context, Bitmap bitmap, File previewFile, File finalFile, Orientation orientation) {
super(context);
mBitmap = bitmap;
mPreviewFile = previewFile;
mFinalFile = finalFile;
mOrientation = orientation;
if(mDeleteBitmap != null)
return;
mDeleteBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.deletebutton);
}
public void deleteFile()
{
if(mPreviewFile != null && mPreviewFile.exists())
{
mPreviewFile.delete();
}
if(mFinalFile != null && mFinalFile.exists())
{
mFinalFile.delete();
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mWidth = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(mWidth, mWidth);
if(mBitmap == null)
return;
mHeight = mWidth;
float bitmapRatio = mBitmap.getWidth() / (float) mBitmap.getHeight();
if(bitmapRatio > 1)
{
mScaledBitmap = Bitmap.createScaledBitmap(mBitmap, mWidth,
(int)(mWidth/bitmapRatio), true);
mPosY = (mWidth-mScaledBitmap.getHeight())/2;
}
else
{
mScaledBitmap = Bitmap.createScaledBitmap(mBitmap, (int)(mHeight*bitmapRatio),
mHeight, true);
mPosX = (mHeight-mScaledBitmap.getWidth())/2;
}
Matrix mtx = new Matrix();
mtx.postRotate(-90);
Bitmap b = Bitmap.createBitmap(mScaledBitmap, 0, 0, mScaledBitmap.getWidth(), mScaledBitmap.getHeight(), mtx, true);
mScaledBitmap = b;
b = null;
mBitmap.recycle();
mBitmap = null;
System.gc();
}
public boolean deleteButtonPressed(float x, float y)
{
Rect r = new Rect(mPosY, mPosX, mPosY+mDeleteBitmap.getWidth(),
mPosX+mDeleteBitmap.getHeight());
if(r.contains((int)x, (int)y))
{
return true;
}
return false;
}
public void setRed(boolean red)
{
mRed = red;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mScaledBitmap, mPosY, mPosX, new Paint());
canvas.drawBitmap(mDeleteBitmap, mPosY, mPosX, new Paint());
if(mRed)
canvas.drawColor(0x55FF0000);
}
}
The "why does it not break" answer's easy. When the visibility of a child view (or container) is set to GONE, the parent layout will (generally) skip it and not even bother rendering it. It's not "hidden", it's not there at all.
If your thumbnails are really thumbnails you shouldn't be running out of memory, however, I think you're not downsampling them (I could be wrong). How are you showing them? You should share that piece of code. (New Photo -> Thumbnail Image -> Image View)
I am so stupid. Obviously my onMeasure() won't be called while the View stays GONE and therefore the original bitmap stays in memory. I changed visibility to INVISIBLE and everything works fine now.
I have a Drawable (a white circle) that I would like to colorize first, and then use it as a Marker in an ItemizedOverlay i.e. I'd like to use the same Drawable to show a green circle and an orange circle on the map.
Simply using setColorFilter on the drawable before calling ItemizedOverlay.setMarker() does not seem to work. I've also tried the mutable Bitmap approach detailed here -
setColorFilter doesn't work on Android < 2.2.
Both approaches simply draw the white circle with no color.
Can someone help me out? I'm running this on Android 2.2.
Thanks!
Update:
I adapted the code from How to change colors of a Drawable in Android? and got it to work for me.
My method looks like this:
private HashMap<Integer, Drawable> coloredPinCache = new HashMap<Integer, Drawable>();
public static final int ORIGINAL_PIN_COLOR = Color.WHITE;
public static final int COLOR_MATCH_THRESHOLD = 100;
protected Drawable getPinInColor(int color) {
// Check if we already have this in the cache
Drawable result = coloredPinCache.get(color);
// If not, create the Drawable
if (result == null) {
// load the original pin
Bitmap original = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
// create a mutable version of this
Bitmap mutable = original.copy(Bitmap.Config.ARGB_8888, true);
// garbage-collect the original pin, since it is not needed further
original.recycle();
original = null;
// loop through the entire image
// set the original color to whatever color we want
for(int x = 0;x < mutable.getWidth();x++){
for(int y = 0;y < mutable.getHeight();y++) {
if(match(mutable.getPixel(x, y), ORIGINAL_PIN_COLOR))
mutable.setPixel(x, y, color);
}
}
// create the Drawable from the modified bitmap
result = new BitmapDrawable(mutable);
// cache this drawable against its color
coloredPinCache.put(color, result);
}
// give back the colored drawable
return result;
}
private boolean match(int pixel, int color) {
return Math.abs(Color.red(pixel) - Color.red(color)) < COLOR_MATCH_THRESHOLD &&
Math.abs(Color.green(pixel) - Color.green(color)) < COLOR_MATCH_THRESHOLD &&
Math.abs(Color.blue(pixel) - Color.blue(color)) < COLOR_MATCH_THRESHOLD;
}
However, this approach is pretty resource-intensive. I'd still like to know if there's a better/faster/smarter way to accomplish this.
Thanks!
I have two png image files that I would like my android app to combine programmatically into one png image file and am wondering if it is possible to do so? if so, what I would like to do is just overlay them on each other to create one file.
the idea behind this is that I have a handful of png files, some with a portion of the image on the left with the rest transparent and the others with an image on the right and the rest transparent. and based on user input it will combine the two to make one file to display. (and i cant just display the two images side by side, they need to be one file)
is this possible to do programmatically in android and how so?
I've been trying to figure this out for a little while now.
Here's (essentially) the code I used to make it work.
// Get your images from their files
Bitmap bottomImage = BitmapFactory.decodeFile("myFirstPNG.png");
Bitmap topImage = BitmapFactory.decodeFile("myOtherPNG.png");
// As described by Steve Pomeroy in a previous comment,
// use the canvas to combine them.
// Start with the first in the constructor..
Canvas comboImage = new Canvas(bottomImage);
// Then draw the second on top of that
comboImage.drawBitmap(topImage, 0f, 0f, null);
// comboImage is now a composite of the two.
// To write the file out to the SDCard:
OutputStream os = null;
try {
os = new FileOutputStream("/sdcard/DCIM/Camera/" + "myNewFileName.png");
comboImage.compress(CompressFormat.PNG, 50, os)
} catch(IOException e) {
e.printStackTrace();
}
EDIT :
there was a typo,
So, I've changed
image.compress(CompressFormat.PNG, 50, os)
to
bottomImage.compress(CompressFormat.PNG, 50, os)
You can do blending. This is not particular to Android. It's just universal image processing.
EDIT:
You may find these articles & samples & code useful:
http://www.jhlabs.com/ip/
http://kfb-android.blogspot.com/2009/04/image-processing-in-android.html
http://code.google.com/p/jjil/
Image Processing on Android
I use this code
private class PhotoComposition extends AsyncTask<Object, Void, Boolean> {
private String pathSave;//path save combined images
#Override
protected Boolean doInBackground(Object... objects) {
List<String> images = (List<String>) objects[0]; //lsit of path iamges
pathSave = (String) objects[1];//path save combined images
if (images.size() == 0) {
return false;
}
List<Bitmap> bitmaps = new ArrayList<>();
for (int i = 0; i < images.size(); i++) {
bitmaps.add(BitmapFactory.decodeFile( images.get(i)));
}
int width = findWidth(bitmaps);//Find the width of the composite image
int height = findMaxHeight(bitmaps);//Find the height of the composite image
Bitmap combineBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);//create bitmap of composite image
combineBitmap.eraseColor(Color.parseColor("#00000000")); //bcakgraound color of composite image
Bitmap mutableCombineBitmap = combineBitmap.copy(Bitmap.Config.ARGB_8888, true);//create mutable bitmap to create canvas
Canvas canvas = new Canvas(mutableCombineBitmap);// create canvas to add bitmaps
float left = 0f;
for (int i = 0; i < bitmaps.size(); i++) {
canvas.drawBitmap(bitmaps.get(i), left, 0f, null);//Taking photos horizontally
left += bitmaps.get(i).getWidth();//Take right to the size of the previous photo
}
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(pathSave);//path of save composite image
mutableCombineBitmap.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean isSave) {
if (isSave) {
//iamge save on pathSave
Log.i("PhotoComposition", "onPostExecute: " + pathSave);
}
super.onPostExecute(isSave);
}
private int findMaxHeight(List<Bitmap> bitmaps) {
int maxHeight = Integer.MIN_VALUE;
for (int i = 0; i < bitmaps.size(); i++) {
if (bitmaps.get(i).getHeight() > maxHeight) {
maxHeight = bitmaps.get(i).getHeight();
}
}
return maxHeight;
}
private int findWidth(List<Bitmap> bitmaps) {
int width = 0;
for (int i = 0; i < bitmaps.size(); i++) {
width += bitmaps.get(i).getWidth();
}
return width;
}
USAGE
List<String> images = new ArrayList<>();
images.add("/storage/emulated/0/imageOne.png");//path of image in storage
images.add("/storage/emulated/0/imageTwo.png");
// images.add("/storage/emulated/0/imageThree");
// ... //add more images
String pathSaveCombinedImage = "/storage/emulated/0/CombinedImage.png";//path save result image
new PhotoComposition().execute(images, pathSaveCombinedImage);
And the result of using the above code will be as follows
You may wish to look into the Canvas object, which would make it easy to do other drawing operations as well. You can just draw your bitmaps onto a canvas where you want them, then save the resulting bitmap.
If they have transparent sections, then if you draw one on top of the other, only the non-transparent portions will overlap. It will be up to you to arrange the bitmaps however you like.
For the separate issue of re-saving your image to a png, use bitmap.compress().
Try this .
public Bitmap mergeBitmap(Bitmap frame, Bitmap img){
Bitmap bmOverlay = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), frame.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(img, 0, 0, null);
canvas.drawBitmap(frame, new Matrix(), null);
return bmOverlay;
}
Returns a bitmap image
Pass two bitmap images to your function as shown below
Bitmap img= mergeBitmap(imgone, imagetwo);
See the entire post or also see merge multiple images in android programmatically