This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Converting a view to Bitmap without displaying it in Android?
I am trying to convert the view into bitmap from following reference link
link text
Now the problem is how can i get the bitmap that is being converted from view only. in the example author has used relativelayout.dispatchDraw(c) but this line is giving me compile time error i.e.
The method dispatchDraw(Canvas) from
the type ViewGroup is not visible
Here is my code and i have written the following code inside onCreate function
Canvas c=null;
//Create Layout
RelativeLayout relativeView ;
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT
);
relativeView = new RelativeLayout(this);
relativeView.setLayoutParams(lp);
//Background of Layout
Bitmap viewBgrnd = BitmapFactory.decodeResource(getResources(),R.drawable.bgblack);
relativeView.setBackgroundDrawable(new BitmapDrawable(viewBgrnd));
//associated with canvas
Bitmap returnedBitmap = Bitmap.createBitmap(320,480,Bitmap.Config.ARGB_8888);
c = new Canvas(returnedBitmap);
Paint paint = new Paint();
//Create Imageview that holds image
ImageView newImage = new ImageView(this);
Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.bgpink);
newImage.setImageBitmap(srcBitmap);
TextView newText = new TextView(this);
newText.setText("This is the text that its going to appear");
c.drawBitmap(viewBgrnd, 0, 0, paint);
relativeView.layout(100, 0, 256, 256);
relativeView.addView(newImage);
relativeView.addView(newText);
// here i am getting compile time error so for timing i have replaced this line
// with relativeView.draw(c);
relativeView.dispatchDraw(c);
Here the returnedBitmap should contain the image of (ImageView and TextView) but this bitmap contains only bacground bitmap of relativeView i.e. bgblack
here is my solution:
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
Enjoy :)
This works for me:
Bitmap viewCapture = null;
theViewYouWantToCapture.setDrawingCacheEnabled(true);
viewCapture = Bitmap.createBitmap(theViewYouWantToCapture.getDrawingCache());
theViewYouWantToCapture.setDrawingCacheEnabled(false);
I believe the view has to be visible (ie. getVisiblity() == View.VISIBLE). If you are trying to capture it but hide it to the user at the same time, you could move it off screen or put something over it.
Related
I have an app that will create a png image of anything the user write in the text field (custom font and color)
What I'm doing is something like this:
Set Typeface, Text Color and Text to a TextView (BG is transparent)
Using the code below, generate the image for the TextView
Bitmap returnedBitmap = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =textView.getBackground();
if (bgDrawable!=null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
// draw the view on the canvas
view.draw(canvas);
FileOutputStream out = null;
out = new FileOutputStream(new File(filename));
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
The problem is that, the quality of the generated image is not the same as what is displayed in the TextView
Is there any way to improve the quality?
Is it because of the TextView not having a background? If so, is there a workaround for this? Need the generated image to only be the text, hence the transparent background
Thanks
I believe the quality depends on the screen size from you create the image. I suggest you to put the Textview in a FrameLayout and create the bitmap from the FrameLayout..
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
I have an image to show as marker, inside that image i have to update time when the map is moving
The problem facing now is
I dont know how to show time inside my custom image.
BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.drawable.ic_remaining_time);
googleMap.addMarker(new MarkerOptions()
.position(cameraPosition.target)
.title(cameraPosition.toString())
.icon(descriptor)
);
Please anyone help me
Make drawable on every time when map get changed or move and set icon like below
marker.setIcon(BitmapDescriptorFactory.fromBitmap(CommonUtils.writeOnDrawable(mContext,R.drawable.ic_location,"your text here").getBitmap()));
// Bitmap Drawable method
public static BitmapDrawable writeOnDrawable(Context context, int drawableId, String text){
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextSize(30);
paint.setTextAlign(Paint.Align.CENTER);
Canvas canvas = new Canvas(bm);
// Change the position of text here
canvas.drawText(text,bm.getWidth()/2 //x position
, bm.getHeight()/2 // y position
, paint);
return new BitmapDrawable(context.getResources(),bm);
}
you can get the marker when u first time add marker in google map object
Marker marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).title(allJob.getBusiness().getName()).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_icon)));
I don't reccomend to update repeatedly a text inside an image in marker because to achieve that you must creat a bitmap with the image and text and put that bitmap as icon marker and that's not free (in terms of memory usage).
But you can try, anyway... Create the bitmap descriptor that way and put inside the icon:
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
view.setLayoutParams( new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT ) );
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap); view.draw(canvas);
return bitmap;
}
Pass to that function the view you can set as icon, inflating an xml maybe.
Try something like this -
BitmapDescriptor descriptor = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getActivity().getResources(),R.drawable.ic_remaining_time));
googleMap.addMarker(new MarkerOptions()
.position(cameraPosition.target)
.title(cameraPosition.toString())
.icon(descriptor)
);
To get customized marker inflate your custom layout at the place of marker like below -
private Bitmap fillCustomizedMarker(int markerResource) {
//Log.d(TAG, "fillMarkerWithText ++");
View markerLayout;
markerLayout = getActivity().getLayoutInflater().inflate(R.layout.custom_marker, null);
markerLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
markerLayout.layout(0, 0, markerLayout.getMeasuredWidth(), markerLayout.getMeasuredHeight());
ImageView markerImage = (ImageView) markerLayout.findViewById(R.id.marker_image);
TextView timeText = (TextView) markerLayout.findViewById(R.id.timeText);
markerImage.setImageResource(markerResource);
markerCost.setText(time);
final Bitmap bitmap = Bitmap.createBitmap(markerLayout.getMeasuredWidth(), markerLayout.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
markerLayout.draw(canvas);
return bitmap;
}
And to update this layout i would suggest you to use handler in android. It will update your UI efficiently.
I am working on an android app and I am trying to create bitmap image from view. My view creation codes are,
private View createInflatedViewFromLayout(Context context, String question, String answer, ViewGroup containerView){
View view;
//Creating view from layout inflater
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.image_export_view, (ViewGroup) containerView.getParent(), false);
//Getting layout and text views
LinearLayout layout = (LinearLayout)view.findViewById(R.id.imageExportLayout);
TextView pre_text_one = (TextView)view.findViewById(R.id.imageLayout_pre_text_one);
TextView pre_text_two = (TextView)view.findViewById(R.id.imageLayout_pre_text_two);
TextView pre_text_three = (TextView)view.findViewById(R.id.imageLayout_pre_text_three);
TextView post_text_one = (TextView)view.findViewById(R.id.imageLayout_post_text_one);
TextView post_text_two = (TextView)view.findViewById(R.id.imageLayout_post_text_two);
//Setting up typeface
pre_text_one.setTypeface(custFont);
pre_text_two.setTypeface(custFont);
pre_text_three.setTypeface(custFont);
post_text_one.setTypeface(custFont);
post_text_two.setTypeface(custFont);
//Setting up text and answer in text views
post_text_one.setText(question);
post_text_two.setText(answer);
//To get random number so we can get color from colors array
Random r = new Random();
int Low = 0;
int High = 5;
int Result = r.nextInt(High-Low) + Low;
layout.setBackgroundColor(Color.parseColor(colors[Result][0]));
post_text_one.setTextColor(Color.parseColor(colors[Result][1]));
post_text_two.setTextColor(Color.parseColor(colors[Result][1]));
return view;
}
So this function is working properly and creating view. I have verified it by codes below,
final LinearLayout testLo = (LinearLayout)convertView.findViewById(R.id.test_lo);
if(testLo.getChildCount() > 0)
testLo.removeAllViewsInLayout();
View lv = createInflatedViewFromLayout(context,
questions[(Integer)v.getTag()],
answers[(Integer)v.getTag()],
finalConvertView);
testLo.addView(lv, 0);
My bitmap image creation function is
public static Bitmap loadBitmapFromView(View v, Context ctx) {
Bitmap b = Bitmap.createBitmap(
2000, 2000, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, 2000, 2000);
v.draw(c);
return b;
}
and when I check the image with these codes,
Bitmap bmp = loadBitmapFromView(testLo.findViewById(0), context);
ImageView image = new ImageView(context);
image.setImageBitmap(bmp);
testLo.addView(image);
All I get is colored background but no text from view. And problem I am facing with with bitmap creation function is that I have to give height and width manually.
I mean if I use these codes,
Bitmap b = Bitmap.createBitmap(
v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getWidth(), v.getHeight());
or these codes,
Bitmap b = Bitmap.createBitmap(
v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
it is crashing app by throwing error that height and width needs to be greater than 0. It is returning -1, -2 etc.
To create bitmap image I have also used below line of code,
Bitmap bmp = loadBitmapFromView(lv, context);
Can anyone tell me where I have problem? What do I need to change to get height, width and create image from layout view.
I'm not sure but I used this boilerplate code for creating bitmaps from my screen - in other words the code below will actually take a screenshot of your phone:
final View v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
If you only want to take a bitmap of a specific view, like a TextView or ImageView, you can just do this:
TextView v = (TextView) findViewById(R.id.example);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
I have RelativeLayout and I want to convert it to the Bitmap like this:
public static Bitmap getBitmapFromView(View view) {
if (view != null)
{ Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
else
return null;
}
then I create RelativeLayout cView in the onCreate() method dynamically and set it to the ImageView like this:
dialer = (ImageView) findViewById(R.id.imageView_ring);
dialer.setImageBitmap(getBitmapFromView(cView));
and get error:
05-20 13:48:27.509: E/AndroidRuntime(28367):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{ru.biovamp.widget/ru.biovamp.widget.TestCircleAct}:
java.lang.IllegalArgumentException: width and height must be > 0
I also tried to add bitmap to the ImageView from the onStart() method, but got the same result. What solution can I use?
I've solved my issue like this:
public Bitmap getBitmapFromView() {
this.measure(MeasureSpec.makeMeasureSpec(createNewRelativeLayoutParams().width, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(createNewRelativeLayoutParams().height, MeasureSpec.UNSPECIFIED));
this.layout(0, 0, this.getMeasuredWidth(), this.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(this.getMeasuredWidth(), this.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
this.draw(c);
return returnedBitmap;
}
so solution is that we should to call measure() and layout() methods before drawing it.
oficial explaniton
I have an image view. I need to display the various text on images.For each image the position of the text gets differ.I will give position value using x,y co ordinates of ImageView.
Any guesses How to perform this?
Create a bitmap
Create a canvas
Draw what you need
Post it to the imageview
Like this:
Bitmap drawingSurface = Bitmap.createBitmap(picBitmap.getWidth(), picBitmap.getHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(drawingSurface);
canvas.drawBitmap(picBitmap, 0, 0, null);
canvas.drawText("Hi!", 10, 10, new Paint());
myImageView.setImageBitmap(drawingSurface);
Encapsulate the image and text in a layout then give coordinates to the views inside their parrent then use theencapsulated view group like your imageview.
Options options = new BitmapFactory.Options();
options.inScaled=false;
Bitmap original;
Bitmap mutable = null;
try{
original = BitmapFactory.decodeResource(this.getResources(), R.drawable.,null);
mutable = original.copy(Bitmap.Config.ARGB_8888, true);
}catch (Exception e) {
// TODO: handle exception
}
Paint paint=new Paint();
paint.setAntiAlias(true);
Canvas c= new Canvas(mutable);
Log.d("density",""+dm.density);
paint.setColor(Color.WHITE);
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(42);
c.drawText("text", (mutable.getWidth()/2)-x,(mutable.getHeight()/2)+y, paint);
BitmapDrawable bitmap = new BitmapDrawable(mutable)
imageView set background drawable bitmap