How to set margin for ImageView in pixels in android java? - java

I have a set of ImageViews whose BackgroundResource and LayoutParams will be defined in a separate xml file. The height, width, marginleft and margintop are given in pixels. The values are in respect to a 1024x600 pixel resolution screen. The code i'm using
ImageView ImgV= (ImageView)findViewById(R.id.ImgV_1);
RelativeLayout.LayoutParams the_dimens = new RelativeLayout.LayoutParams(50,50);
the_dimens.setMargins(800,50,0,0);
ImgV.setBackgroundResource(R.drawable.bulbon);
ImgV.setLayoutParams(the_dimens);
While the height and width seem to be rightly displayed in pixels, the margins are not. So how can I set the margin values to apply in pixels rather than whatever default units the below code takes.
the_dimens.setMargins(800,50,0,0);
The app is only for a 1024x600 device, so i'm not worried about resolution independent design.
Thanks.

check this
int dpValue = 5; // margin in dips
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(dpValue * d); // margin in pixels

You can do in this way:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);

Related

Adding an ImageView at a random position in a LinearLayout

I want to add image views dynamically to a full screen linear layout. I have written some code but some image views are either partially or totally going outside the screen. Some times image views are well within the phone screen.
How can I ensure that they remain totally inside the screen.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int widthArea = displayMetrics.widthPixels;
final int heightArea = displayMetrics.heightPixels;
final LinearLayout home = (LinearLayout) findViewById(R.id.llHome);
ImageView imgView = new ImageView(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, 200);
imgView.setLayoutParams(lp);
imgView.setImageResource(R.drawable.img_1);
imgView.setX(r.nextInt(widthArea));
imgView.setY(r.nextInt(heightArea));
home.addView(imgView);
You should take into account the dimension of the image itself. Settings X and Y place its starting point within the screen but it might leak on a side.
First, load your image as a Drawable, then include drawable.getWidth() (and maybe even height, that depends on your layout) to your X position.
imgView.setX(r.nextInt(widthArea - drawable.getWidth()) + drawable.getWidth());

Android get rid of DialogFragment floating margin

I'm displaying a dialogfragment in my app and I notice that even when I set the fragments' y position to the bottom of the screen there's still a margin visible:
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
windowParams.y = size.y;
In the below screenshot you can see that the light blue (my dialogfragment) is still appearing some distance away from the bottom of the screen despite being set to the bottom of the screen. How do I remove this margin?
The solution is to add this line:
setStyle(DialogFragment.STYLE_NO_FRAME, 0);
To avoid extra margin in bottom, top , left and right use below lines of code.
//Dialog fragment will be shown at the bottom of screen
//if you want to show on entire screen just comment it
getDialog().getWindow().setGravity(Gravity.BOTTOM);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = getDialog().getWindow();
lp.copyFrom(window.getAttributes());
//This makes the dialog take up the full width
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//For full height set it to MATCH_PARENT else WRAP_CONTENT
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);

Camera not stretching to width of android device

In my android camera app, Im trying to make it so that the camera layout view fills the width of the screen and then is proportional (to a square) for the height of the layout. But its cropping it too small for some reason:
example of what is happening..
The green arrow represents where it should go to.
Ive tried fill_parent, etc. So, how can I make it go to the end of the screen?
I believe this is the problem. I know I did this because I was not sure how to make it automatically stretch to the right proportion.
int width = 352;
int height = 288;
camPreview = new CameraSurfaceView(width, height);
myCamHolder.addCallback(camPreview);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = width*288/352;
Maybe you don't need 288/352, but rather preview size.height/preview size.width

Android Imageview: Measure unspecified to calculate Bitmap dimensions

Google suggests to load Bitmaps from resources scaled down, depending on the actual ImageView size ("Loading Large Bitmaps Efficiently" at googles developer guides). Therefor, I have to know the width and height of the ImageView before I can decode the bitmap.
My code looks something like the one posted below. decodeSampledBitmapFromResources returns the bitmap as a scaled down version of the one stored in resources.
public void onCreate(Bundle savedInstanceSate)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout)
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
/**
At this point, I need to calculate width and height of the ImageView.
**/
Bitmap bitmap = MyBitmapManager.decodeSampledBitmapFromResource(
getResources(), R.drawable.my_icon, width, height);
imageView.setImageBitmap(bitmap);
}
The problem is, as I am in onCreate, my ImageView does not have any width and height, yet. getWidth() and getHeight() are just returning 0. I stumbled over this code to calculate the size of a view before it is actually drawn:
ImageView v = findViewById(R.id.myImageView);
v.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = v.getMeasuredWidth();
int height = v.getMeasuredHeight();
Is this suitable for my situation? I tried it and the above code returns some values for width and height which seem to be correct, but Im not sure if this is the correct way to do it.
UPDATE:
After some more testing, this seems NOT to work.
In the above example, im using a PNG with a size of 192x192 pixels.
After measureing the ImageView as seen above, i get a measured dimension of 128x128.
If I call getWidth() and getHeight() AFTER the bitmap is set to the imageview, the dimension is 100x100.
So in this scenario, the image is downsized from 192x192 to 128x128, but not to 100x100 as it should be.
It seems that Measurespec.UNSPECIFIED always returns dimensions greater than they are at the end.
Thanks in advance,
danijoo
I got it solved on my own with this:
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw(){
// at this point, true width and height are already determined
int width = imageView.getMeasuredWidth();
int height = imageView.getMeasuredHeight();
Bitmap bitmap = MyBitmapManager.decodeSampledBitmapFromResource(
getResources(), R.drawable.my_icon, width, height);
imageView.setImageBitmap(bitmap);
// this is important because onPreDrawn is fired multiple times
imageView.getViewTreeObserver().removeOnPreDrawListener(this);
return true;
}
}

How to set unit for Paint.setTextSize()

Is it possible to change the unit for Paint.setTextSize()? As far as I know, it's pixel but I like to set the text size in DIP for multiple screen support.
I know this topic is old and already answered but I would like to also suggest this piece of code:
int MY_DIP_VALUE = 5; //5dp
int pixel= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
MY_DIP_VALUE, getResources().getDisplayMetrics());
Convert it like this
// The gesture threshold expressed in dip
private static final float GESTURE_THRESHOLD_DIP = 16.0f;
// Convert the dips to pixels
final float scale = getContext().getResources().getDisplayMetrics().density;
mGestureThreshold = (int) (GESTURE_THRESHOLD_DIP * scale + 0.5f);
// Use mGestureThreshold as a distance in pixels
from here http://developer.android.com/guide/practices/screens_support.html#dips-pels
The accepted answer is for gestures, not setting text size. The highest voted answer (at the time of this writing) is close, but the documentation recommends using sp rather than dp because in addition to being scaled for screen densities (as dp values are), sp is also scaled according to user preferred font sizes.
From an int in code
int spSize = 17;
float scaledSizeInPixels = spSize * getResources().getDisplayMetrics().scaledDensity;
mTextPaint.setTextSize(scaledSizeInPixels);
Or alternatively
int spSize = 17;
float scaledSizeInPixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spSize, getResources().getDisplayMetrics());
mTextPaint.setTextSize(scaledSizeInPixels);
From resources
Or if you have the sp or dp value in resources:
<resources>
<dimen name="fontSize">17sp</dimen>
</resources>
with
float scaledSizeInPixels = getResources().getDimensionPixelSize(R.dimen.fontSize);
mTextPaint.setTextSize(scaledSizeInPixels);
Other links
How to convert DP, PX, SP among each other, especially DP and SP?
Android: Canvas.drawText() text size on different screen resolutions
Paint.setTextSize
getDimensionPixelSize
And here is even shorter method to convert dp-s to px-els taking display metrics into account
https://developer.android.com/reference/android/content/res/Resources.html#getDimensionPixelSize(int)
If your Paint object is being used to draw text on a Canvas, you can let the Canvas handle scaling for you.
When calling Canvas.drawText() the text size is first determined by the passed in Paint object, which can be set via Paint.setTextSize(). The text size is automatically scaled by Canvas based on the canvas density, which can be found using Canvas.getDensity().
When setting the text size on a paint object that will be drawn on Canvas, work with a unit value of dp or sp and let Canvas handle the scaling for you.

Categories

Resources