I want to create android custom SeekBar having thumb with text inside it to show current seek position.
Here is my code:
SeekBar sb;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_seek_bar_activity);
sb = (SeekBar)findViewById(R.id.slider);
sb.setMax(100);
sb.setProgress(10);
BitmapDrawable bd = writeOnDrawable(R.drawable.star2, Double.toString(50));
sb.setThumb(bd);
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
int pos = sb.getProgress();
double star = pos/(20.0);
TextView tv = (TextView)findViewById(R.id.percent);
tv.setText(Double.toString(star)+"%");
BitmapDrawable bd = writeOnDrawable(R.drawable.star2, Double.toString(star));
bd.setBounds(new Rect(0,0,
bd.getIntrinsicWidth(),
bd.getIntrinsicHeight()
));
seekBar.setThumb(bd);
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
});
}
public BitmapDrawable writeOnDrawable(int drawableId, String text){
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.BLACK);
paint.setTextSize(10);
Canvas canvas = new Canvas(bm);
canvas.drawText(text, 0, bm.getHeight()/2, paint);
return new BitmapDrawable(bm);
}
but when I move thumb it goes to the beginning of the seek bar.
Does anyone have solution to move custom thumb with seekbar position?
I use SeekBar to display a timer countdown in my app. Inside the timer thumb I show the current SeekBar progress number using the below code:
SeekBar timerBar = (SeekBar) findViewById(R.id.seekBarTimer);
if (timerBar != null) {
timerBar.setMax((int) (Settings.countdownSeconds + 1));
timerBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar timerBar, int arg1, boolean arg2) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.seek_thumb);
Bitmap bmp = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas c = new Canvas(bmp);
String text = Integer.toString(timerBar.getProgress());
Paint p = new Paint();
p.setTypeface(Typeface.DEFAULT_BOLD);
p.setTextSize(14);
p.setColor(0xFFFFFFFF);
int width = (int) p.measureText(text);
int yPos = (int) ((c.getHeight() / 2) - ((p.descent() + p.ascent()) / 2));
c.drawText(text, (bmp.getWidth()-width)/2, yPos, p);
timerBar.setThumb(new BitmapDrawable(getResources(), bmp));
}
});
timerBar.setProgress(0);
}
The R.drawable.seek_thumb drawable is my thumb drawable.
I got solution now, in setBound() method I was passing top left as 0, that's why it is showing seek bar at beginning. After doing following change I got it works.
Call setThumbPos() method in onProgressChanged() event
public void setThumbPosition(SeekBar seekBar){
int max = seekBar.getMax();
int available = seekBar.getWidth() - seekBar.getPaddingLeft() - seekBar.getPaddingRight();
float scale = max > 0 ? (float) seekBar.getProgress() / (float) max : 0;
//scale = 1;
int pos = sb.getProgress();
double star = pos/(20.0);
BitmapDrawable bd = writeOnDrawable(R.drawable.star2, Double.toString(star));
int thumbWidth = bd.getIntrinsicWidth();
int thumbHeight = bd.getIntrinsicHeight();
//available -= thumbWidth;
int thumbPos = (int) (scale * available);
if(thumbPos <= 0+thumbWidth){
thumbPos += (thumbWidth/2);
}else if(thumbPos >= seekBar.getWidth()-thumbWidth){
thumbPos -= (thumbWidth/2);
}
bd.setBounds(new Rect(thumbPos,0,
thumbPos+bd.getIntrinsicWidth(),
bd.getIntrinsicHeight()
));
seekBar.setThumb(bd);
TextView tv = (TextView)findViewById(R.id.percent);
tv.setText(Double.toString(star)+"%");
}
I ended up using this simple solution. Its probably not as high-performance as say a proper custom SeekBar, however its really easy to plug into an existing layout, and use any label or other view on top of the SeekBar thumb.
protected void positionThumbLabel(SeekBar seekBar, TextView label)
{
Rect tr = seekBar.getThumb().getBounds();
label.setWidth(tr.width());
label.setX(tr.left + seekBar.getPaddingLeft());
}
With some minor changes you can position an overlay relative to the center of the thumb:
protected void positionThumbOverlayCenter(SeekBar seekBar, View overlay)
{
Rect tr = seekBar.getThumb().getBounds();
overlay.setX(tr.centerX() - (overlay.getWidth() * 0.5f) + seekBar.getPaddingLeft());
}
Pick a solution that match your situation here: http://www.helptouser.com/code/10722746-add-dynamic-text-over-android-seekbar-thumb.html
Related
I am new to Android and I am trying to Build a gallery app with Edit Activity. I have attached the screenshot of edit screen of my app. There is an ImageView, a SeekBar and 4 ImageButtons. The ImageButtons implements 4 edit functionality-Brightness,saturation and etc.. I have all methods for effects. All I want to know is when I click the imageButton(may be brightness), and drag the seekbar, the brightness should increase and similarly, when i click Contrast ImageButton and drag the seekbar, Contrast of Image should Increase. How can I implement it. Could Someone Please help me with it.. I tried using setOnTouchListener() for ImageButtons but that dint work, as it accepts only view as parameter and not Bitmap. Please help me.Thanks in Advance
Below is my Edit Activity
public class EditActivity extends Activity
{
private Bitmap bitmap;
private ImageView image;
private ImageButton bb,sab,shb,cb;
private BitmapDrawable drawable;
private SeekBar seekBar;
#Override
public void onCreate( Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.filters);
// Get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
image = (ImageView) findViewById(R.id.imageView);
image.setImageResource(imageAdapter.ids[position]);
bb = (ImageButton) findViewById(R.id.brightButton);
drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
bb.setImageBitmap(bitmap);
sab=(ImageButton)findViewById(R.id.saturationButton);
drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
sab.setImageBitmap(bitmap);
cb=(ImageButton) findViewById(R.id.contrastButton);
drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
cb.setImageBitmap(bitmap);
shb=(ImageButton) findViewById(R.id.sharpButton);
drawable = (BitmapDrawable) image.getDrawable();
bitmap = drawable.getBitmap();
shb.setImageBitmap(bitmap);
SeekBar seekBar=(SeekBar)findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
int brightness;
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2)
{
brightness = progress;
Bitmap bBitMap = brightClicked(bitmap,progress);
image.setImageBitmap(bBitMap);
Bitmap saBitMap = sharpClicked(bitmap,progress);
image.setImageBitmap(saBitMap);
Bitmap cBitMap = saturationClicked(bitmap,progress);
image.setImageBitmap(cBitMap);
Bitmap shBitMap = contrastClicked(bitmap,progress);
image.setImageBitmap(shBitMap);
}
});
}
public Bitmap brightClicked(Bitmap bbitmap,int value)
{
Bitmap bmOut= Bitmap.createBitmap(bbitmap.getWidth(), bbitmap.getHeight(),bbitmap.getConfig());
int A, R, G, B;
int pixel;
for(int i=0; i<bbitmap.getWidth(); i++){
for(int j=0; j<bbitmap.getHeight(); j++)
{
pixel = bbitmap.getPixel(i, j);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
R += value;
if (R > 255)
{
R = 255;
} else if (R < 0)
{
R = 0;
}
G += value;
if (G > 255)
{
G = 255;
} else if (G < 0)
{
G = 0;
}
B += value;
if (B > 255)
{
B = 255;
} else if (B < 0)
{
B = 0;
}
bmOut.setPixel(i, j, Color.argb(A, R, G, B));
}
}
return bmOut;
}// and other methods of effects like sharpness,contrast..
Below is Screenshot of EditImage
I would begin with defining state so that the SeekBar can quickly determine which attribute it should be modifying (contrast, brightness, sharpness, saturation). Throw these into an enum class (Google recommends avoiding enums in Android) if you like or define them within the class itself as ints. For example:
public class EditActivity extends Activity {
private int currentState;
private static final int SATURATE = 0;
private static final int CONTRAST = 1;
....
}
Now you can just have the state be updated based on the button clicked:
bb = (ImageButton) findViewById(R.id.brightButton);
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentState = BRIGHTNESS;
}
}
Then use a switch-case statement to quickly determine the state of the Activity and adjust the image accordingly through your image methods.
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2)
{
brightness = progress;
switch (currentState) {
case (SATURATE) :
image.setImageBitmap(saturationClicked(bitmap,progress));
break;
case (CONTRAST) :
image.setImageBitmap(contrastClicked(bitmap,progress));
break;
It looks like your current implementation would run all your filters on the image any time the seek bar is moved, which I imagine would cause horrible performance. A switch case would just help you avoid that.
I am trying to create a ProgresBar that looks like the following:
So far, I have created an object which extends ProgressBar, and now I am trying to figure out what my next step is.
I know that I need to override onDraw() with some logic that will decide how many squares to color in. This is trivial.
What I don't know how to do is get these squares in the first place. How can I replace the default drawable, so when I add my custom bar in the layout I can see something like my image?
try this custom Drawable:
class ProgressDrawable extends Drawable {
private static final int NUM_RECTS = 10;
Paint mPaint = new Paint();
#Override
protected boolean onLevelChange(int level) {
invalidateSelf();
return true;
}
#Override
public void draw(Canvas canvas) {
int level = getLevel();
Rect b = getBounds();
float width = b.width();
for (int i = 0; i < NUM_RECTS; i++) {
float left = width * i / NUM_RECTS;
float right = left + 0.9f * width / NUM_RECTS;
mPaint.setColor((i + 1) * 10000 / NUM_RECTS <= level? 0xff888888 : 0xffbbbbbb);
canvas.drawRect(left, b.top, right, b.bottom, mPaint);
}
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
and test it with the following in onCreate:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final ProgressBar pb = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
Drawable d = new ProgressDrawable();
pb.setProgressDrawable(d);
pb.setPadding(20, 20, 20, 0);
ll.addView(pb);
OnSeekBarChangeListener l = new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int newProgress = pb.getMax() * progress / seekBar.getMax();
Log.d(TAG, "onProgressChanged " + newProgress);
pb.setProgress(newProgress);
}
};
int[] maxs = {4, 10, 60, 110};
for (int i = 0; i < maxs.length; i++) {
SeekBar sb = new SeekBar(this);
sb.setMax(maxs[i]);
sb.setOnSeekBarChangeListener(l);
sb.setPadding(20, 20, 20, 0);
ll.addView(sb);
}
setContentView(ll);
I trying to make a draw line using canvas. It has 0 value when the Activity is loaded then I have a Button that has click listener to change the value and draw a line. It works in emulator well but when I run in my real device (android version 4.1) the canvas didn't change but I know that I hit the button because I put a toast inside the click listener. This is really weird.
Do anyone encounter the same problem before?
any thoughts will be highly appreciated.
Below is my Activity:
public class MainActivity extends Activity{
private Paint paintFree = new Paint();
private Paint paintLocal = new Paint();
private Paint paintRoaming = new Paint();
private int freeUsage = 0;
private int localUsage = 0;
private int roamingUsage = 0;
private int freeBarPoints;
private int localBarPoints;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
overridePendingTransition(0, 0);
line();
((Button) findViewById(R.id.btn1)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
freeUsage = 12;
localUsage = 1;
roamingUsage = 1;
line();
Log.i("Hit Btn1", "True");
Toast.makeText(v.getContext(), "Hit Btn1", Toast.LENGTH_SHORT).show();
}
});
}
class Draw extends View{
public Draw(Context context) {
super(context);
// TODO Auto-generated constructor stub
paintFree.setStrokeWidth(20f);
paintLocal.setStrokeWidth(20f);
paintRoaming.setStrokeWidth(20f);
if (freeUsage == 0){
paintFree.setColor(Color.GRAY);
} else {
paintFree.setColor(Color.rgb(70, 227, 78));
}
if (localUsage == 0){
paintLocal.setColor(Color.GRAY);
} else {
paintLocal.setColor(Color.rgb(238, 232, 102));
}
if (roamingUsage == 0){
paintRoaming.setColor(Color.GRAY);
} else {
paintRoaming.setColor(Color.rgb(101, 177, 231));
}
}
protected void onDraw(Canvas canvas) {
int maxBarLength = canvas.getWidth() * 4 / 5;
double totalBarPoints = freeUsage + localUsage + roamingUsage;
freeBarPoints = (int) Math.round(freeUsage * maxBarLength / totalBarPoints);
localBarPoints = (int) Math.round(localUsage * maxBarLength / totalBarPoints);
// need not compute the roaming bar points
int localStartX = 0 + Math.round(freeBarPoints);
int roamingStartX = (int) localStartX + Math.round(localBarPoints);
canvas.drawLine(0, 10, localStartX, 10, paintFree);
canvas.drawLine(localStartX, 10, roamingStartX, 10, paintLocal);
canvas.drawLine(roamingStartX, 10, maxBarLength, 10, paintRoaming);
}
}
public void line(){
Draw draw;
draw = new Draw(this);
((LinearLayout) findViewById(R.id.linear)).addView(draw);
}
}
You need to add an onMeasure implementation to your Draw class. Take a look at http://developer.android.com/training/custom-views/custom-drawing.html for more details.
So, I have created an android activity that draws a triangle on the canvas. I also added 4 menus(Color, Enlarge, Shrink, and Reset) to the VM. The color works fine but I'm not quite sure how to resize a triangle in android once that menu button is pressed.The assignment says to just fix the top point of the triangle, and then change the coordinates of the bottom two points of the triangle. Can anyone point me in the right direction on how to do that in Android?
Here's my code, although the implementation of enlarge, shrink, and reset are set up to work with a circle(project I did before), not a triangle. Please note that the "Color" menu works so no need to do that.
public class MainActivity extends Activity
{
final Context context = this;
private Graphics graphic;
private Dialog radiusDialog; //Creates dialog box declaration
private SeekBar red;
private SeekBar green;
private SeekBar blue;
private Button radiusButton;
private TextView progress1;
private TextView progress2;
private TextView progress3;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
graphic = new Graphics(this); //Create new instance of graphics view
setContentView(graphic); //Associates customized view with current screen
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) //This acts as a menu listener to override
{
switch(item.getItemId()) //returns menu item
{
case R.id.Color:
showDialog();
break;
case R.id.Shrink:
graphic.setRadius(graphic.getRadius() -1);
graphic.invalidate();
break;
case R.id.Enlarge:
graphic.setRadius(graphic.getRadius() +1);
graphic.invalidate();
break;
case R.id.Reset:
graphic.setColor(Color.CYAN);
graphic.setRadius(75);
graphic.invalidate();
break;
}
return super.onOptionsItemSelected(item);
}
void showDialog() //creates memory for dialog
{
radiusDialog = new Dialog(context);
radiusDialog.setContentView(R.layout.draw_layout); //binds layout file (radius) with current dialog
radiusDialog.setTitle("Select Color:");
red = (SeekBar)radiusDialog.findViewById(R.id.seekBar1);
green = (SeekBar)radiusDialog.findViewById(R.id.seekBar2);
blue = (SeekBar)radiusDialog.findViewById(R.id.seekBar3);
progress1 = (TextView)radiusDialog.findViewById(R.id.textView2);
progress2 = (TextView)radiusDialog.findViewById(R.id.textView4);
progress3 = (TextView)radiusDialog.findViewById(R.id.textView6);
mychange redC = new mychange();
red.setOnSeekBarChangeListener(redC);
mychange greenC = new mychange();
green.setOnSeekBarChangeListener(greenC);
tv = (TextView)radiusDialog.findViewById(R.id.textView7);
mychange c = new mychange();
blue.setOnSeekBarChangeListener(c);
radiusButton = (Button) radiusDialog.findViewById(R.id.button1);
radiusButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int color = Color.rgb(red.getProgress(), green.getProgress(), blue.getProgress());
radiusDialog.dismiss();
setContentView(R.layout.activity_main);
setContentView(graphic);
graphic.setColor(color);//Create new instance of graphics view
graphic.invalidate();
}
});
radiusDialog.show(); //shows dialog on screen
}
public class mychange implements OnSeekBarChangeListener{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
int color = Color.rgb(red.getProgress(), green.getProgress(), blue.getProgress());
tv.setBackgroundColor(color);
progress1.setText(String.valueOf(red.getProgress()));
progress2.setText(String.valueOf(green.getProgress()));
progress3.setText(String.valueOf(blue.getProgress()));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
}
Graphics Class to draw triangle
public class Graphics extends View
{
private Paint paint;
private int radius;
private int color;
public void setColor(int color)
{
this.color = color;
}
public Graphics(Context context) //creates custom view (constructor)
{
super(context);
paint = new Paint(); //create instance of paint
color = Color.CYAN;
paint.setStyle(Paint.Style.FILL); //draw filled shape
radius = 75;
}
#Override
protected void onDraw(Canvas canvas) //override onDraw method
{
super.onDraw(canvas);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
Path path = new Path();
path.moveTo(230, 200);
path.lineTo(330, 300);
path.lineTo(130, 300);
path.close();
canvas.drawPath(path, paint);
}
void setRadius(int radius)
{
this.radius = radius;
invalidate(); //just like repaint method
}
public int getRadius()
{
return radius;
}
}
If the top coordinate remains fixed, you can change the height of the triangle to shrink/enlarge it.
Lets say the triangle is equilateral - all 3 sides have the same length. In this case:
So if the top vertex coordinates are (x, y), the bottom coordinates will be:
(x - side / 2, y + h)
And:
(x + side / 2, y + h)
So your path code should be written as:
float side = Math.sqrt(3) / 2 * height;
Path path = new Path();
path.moveTo(x, y);
path.lineTo(x - side / 2, y + height);
path.lineTo(x + side / 2, y + height);
path.close();
I am a programmer with a Windows background and I am new to Java and Android stuff.
I want to create a widget (not an app) which displays a chart. After a long research I know I can do this with Canvas, imageviews and Bitmaps. The canvas which I paint on should be the same as the Widget Size.
How do I know the widget size (or imageview size) so that I can supply it to the function?
Bitmap.createBitmap(width_xx, height_yy, Config.ARGB_8888);
Code Snippet:
In the timer run method:
#Override
public void run() {
Bitmap bitmap = Bitmap.createBitmap(??, ??, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Create a new paint
Paint p = new Paint();
p.setAntiAlias(true);
p.setStrokeWidth(1);
// Draw circle
// Here I can use the width and height to scale the circle
canvas.drawCircle(50, 50, 7, p);
remoteViews.setImageViewBitmap(R.id.imageView, bitmap);
From what I've learnt, you can only calculate widget dimensions on Android 4.1+.
When on a lower API, you'll have to use static dimensions.
About widget dimensions: App Widget Design Guidelines
int w = DEFAULT_WIDTH, h = DEFAULT_HEIGHT;
if ( Build.VERSION.SDK_INT >= 16 ) {
Bundle options = appWidgetManager.getAppWidgetOptions(widgetId);
int maxW = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
int maxH = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
int minW = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
int minH = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
if ( context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ) {
w = maxW;
h = minH;
} else {
w = minW;
h = maxH;
}
}
Have a look at the method:
public void onAppWidgetOptionsChanged (Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions)
It will be called each time you start/resize the widget.
Getting the widget width/height can be done as follows:
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)
I am currently using this:
private void run() {
int width = 400, height = 400;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
Paint p = new Paint();
p.setColor(Color.WHITE);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(1);
p.setAntiAlias(true);
c.drawCircle(width/2, height/2, radius, p);
remoteViews.setImageViewBitmap(R.id.imageView, bitmap);
ComponentName clockWidget = new ComponentName(context,
Clock_22_analog.class);
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
appWidgetManager.updateAppWidget(clockWidget, remoteViews);
}
You can use this
Bitmap image1, image2;
Bitmap bitmap = Bitmap.createBitmap(image1.getWidth(), image1.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
You can create a custom widget and set the size of wight on its onMeasure() method. And also save the size at that time so that you can use it further for image creation...
I've not worked on Widgets, but I have some experience getting ImageView's size.
Here is some code I use:
public class ViewSizes {
public int width;
public int height;
public boolean isEmpty() {
boolean result = false;
if (0 >= width || 0 >= height) {
result = true;
}
return result;
}
}
That's just a dummy class containing the size parameters.
public static ViewSizes getSizes(View view) {
ViewSizes sizes = new ViewSizes();
sizes.width = view.getWidth();
sizes.height = view.getHeight();
if (sizes.isEmpty()) {
LayoutParams params = view.getLayoutParams();
if (null != params) {
int widthSpec = View.MeasureSpec.makeMeasureSpec(params.width, View.MeasureSpec.AT_MOST);
int heightSpec = View.MeasureSpec.makeMeasureSpec(params.height, View.MeasureSpec.AT_MOST);
view.measure(widthSpec, heightSpec);
}
sizes.width = view.getMeasuredWidth();
sizes.height = view.getMeasuredHeight();
}
return sizes;
}
This method calculates the width forcing a measure cycle if such has not already happened.
public static boolean loadPhoto(ImageView view, String url, float aspectRatio) {
boolean processed = false;
ViewSizes sizes = ViewsUtils.getSizes(view);
if (!sizes.isEmpty()) {
int width = sizes.width - 2;
int height = sizes.height - 2;
if (ASPECT_RATIO_UNDEFINED != aspectRatio) {
if (height * aspectRatio > width) {
height = (int) (width / aspectRatio);
} else if (height * aspectRatio < width) {
width = (int) (height * aspectRatio);
}
}
// Do you bitmap processing here
processed = true;
}
return processed;
}
This one is probably useless for you. I give just as an example - I have an ImageView and image URL, which should be parametrized with image and height.
public class PhotoLayoutListener implements OnGlobalLayoutListener {
private ImageView view;
private String url;
private float aspectRatio;
public PhotoLayoutListener(ImageView view, String url, float aspectRatio) {
this.view = view;
this.url = url;
this.aspectRatio = aspectRatio;
}
boolean handled = false;
#Override
public void onGlobalLayout() {
if (!handled) {
PhotoUtils.loadPhoto(view, url, aspectRatio);
handled = true;
}
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
removeLayoutListenerPre16(viewTreeObserver, this);
} else {
removeLayoutListenerPost16(viewTreeObserver, this);
}
}
}
#SuppressWarnings("deprecation")
private void removeLayoutListenerPre16(ViewTreeObserver observer, OnGlobalLayoutListener listener){
observer.removeGlobalOnLayoutListener(listener);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void removeLayoutListenerPost16(ViewTreeObserver observer, OnGlobalLayoutListener listener){
observer.removeOnGlobalLayoutListener(listener);
}
}
This is just a layout listener - I want to process the image loading once the layout phase has finished.
public static void setImage(ImageView view, String url, boolean forceLayoutLoading, float aspectRatio) {
if (null != view && null != url) {
final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (forceLayoutLoading || !PhotoUtils.loadPhoto(view, url, aspectRatio)) {
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new PhotoLayoutListener(view, url, aspectRatio));
}
}
}
}
This is the method I actually call. I give it the view and URL. The methods takes care of loading - if it can determine the view's size it starts loading immediately. Otherwise it just assigns a layout listener and start the loading process once the layout is finished.
You could strip away some parameters - forceLoading / aspectRatio should be irrelevant for you. After that change the PhotoUtils.loadPhoto method in order to create the bitmap with the width / height it has calculated.
Like Julian told us, you can get them like that with a bitmap of your image:
int width = bitmap.getWidth();
int height = bitmap.getHeight();