Android Board Game Implementation - android

So I'm creating a board game that uses a 9x9 board with different images for the edges/corners and the middle of the board. After doing a lot of research, people seem to recommend using a TableLayout with buttons or imageButtons for each individual space on the board.
What I am wondering is that in my game, the pieces can also be rotated by 45 degrees each turn. My original plan was to simply have the pieces as part of the imageButton, but I am not sure how I could rotate it. One option that I can think of would be to simply have an individual image for each 45deg rotation, but this seems extremely inefficient as it would require 8 images per piece.
Questions:
Is a tablelayout the proper way to implement my board?
Should I be using imagebuttons for each space on my board?
What would be the best way to rotate my pieces? Should I use a canvas approach for the entire game?
Thank you and please let me know if anything isn't clear.

Yes table layout is a good aproach for this kind of layout IMO
If you have to push on the image you can use ImageButtons, otherwise just use ImageView.
You can rotate a drawable the following way.
private void updateImageOrientation(final float rotationAngle) {
// rotate compass to right orientation
final ImageView img = (ImageView) findViewById(R.id.actMyDrawableImage);
// only if imageView in layout
if (img != null) {
final Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.act_my_drawable);
// Getting width & height of the given image.
final int w = bmp.getWidth();
final int h = bmp.getHeight();
// Setting post rotate to rotation angle
final Matrix mtx = new Matrix();
// Log.v(LOG_TAG, "Image rotation angle: " + rotationAngle);
mtx.postRotate(rotationAngle, (float) (w / 2.0), (float) (h / 2.0));
// Rotating Bitmap
final Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, w, h, mtx, true);
final BitmapDrawable bmd = new BitmapDrawable(getResources(), rotatedBMP);
img.setImageDrawable(bmd);
}
}
Edit 1:
To use ImageButton just replace ImageView by ImageButton in he code above.
final ImageButton img = (ImageButton) findViewById(R.id.actMyDrawableImage);
img.setImageDrawable(drawable)
Edit 2
To show your pieces above your board you could use a FrameLayout for each of your cell. The background would be set:
using an ImageView as below
with a background flag on the FrameLayout (android:background)
if you want one background for your board with a background flag on the parent TableLayout
You can make your pieces visible/invisible programatically:
img.setVisibility(View.VISIBLE);
img.setVisibility(View.INVISIBLE);
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/actMyDrawableButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible" >
</ImageView>
<ImageButton
android:id="#+id/actMyDrawableButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" >
</ImageButton>
</FrameLayout>

Related

Scale ImageView and clip bottom only when outside parent view?

how does one scale an ImageView, yet still have it clip (bottom only) when it/parts of it are outside its parent view?
My code;
XML has 3 elements; image in raw size, view 200px high, view 150px high.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="1000px"
android:layout_height="850px"
android:background="#FFFEC6"
android:orientation="vertical">
<!-- single image in raw size -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fauxcard"
/>
<!-- should be SCALED with NO CLIPPING -->
<RelativeLayout
android:id="#+id/Wrapper1"
android:layout_width="1000px"
android:layout_height="200px"
android:background="#cccccc">
</RelativeLayout>
<!-- should be SCALED with the BOTTOM CLIPPED -->
<RelativeLayout
android:id="#+id/Wrapper2"
android:layout_width="1000px"
android:layout_height="150px"
android:background="#C6FFD1"
android:clipChildren="true">
</RelativeLayout>
</LinearLayout>
java;
RelativeLayout r1 = (RelativeLayout) findViewById(R.id.Wrapper1);
RelativeLayout r2 = (RelativeLayout) findViewById(R.id.Wrapper2);
int marginLeft = 0;
for (int i = 0; i < 10; i++)
{
// IV 1 - the parent view for these is the correct 200 high, so these will be unclipped/unscaled
ImageView myImg1 = new ImageView(this);
myImg1.setImageResource(R.drawable.fauxcard);
RelativeLayout.LayoutParams layout1 = new RelativeLayout.LayoutParams(100, 200);
layout1.setMargins(marginLeft, 0, 0, 0);
r1.addView(myImg1, layout1);
// IV 2 - the parent view for these is NOT high enough (only 150 high), so I want these SCALED but CLIPPED (bottom of image clipped)
ImageView myImg2 = new ImageView(this);
myImg2.setImageResource(R.drawable.fauxcard);
// scaling
// myImg2.setScaleType(ImageView.ScaleType.CENTER); // NOT scaled - clipped
// myImg2.setScaleType(ImageView.ScaleType.CENTER_INSIDE); // scaled - NOT clipped
myImg2.setScaleType(ImageView.ScaleType.CENTER_CROP); // scaled - clipped at TOP and bottom
// myImg2.setScaleType(ImageView.ScaleType.FIT_END); // scaled TOO MUCH - clip not needed
// myImg2.setScaleType(ImageView.ScaleType.FIT_START); // scaled TOO MUCH - clip not needed
// myImg2.setScaleType(ImageView.ScaleType.FIT_CENTER); // scaled TOO MUCH - clip not needed
// myImg2.setScaleType(ImageView.ScaleType.FIT_XY); // scaled incorrect ratio - clip not needed
// myImg2.setScaleType(ImageView.ScaleType.MATRIX); // NOT scaled - clipped
RelativeLayout.LayoutParams layout2 = new RelativeLayout.LayoutParams(100, 200);
layout2.setMargins(marginLeft, 0, 0, 0);
r2.addView(myImg2, layout2);
// I am using marginLeft as my real scenario is more complex - there are varying gaps between the images based on other logic
// the important issue is CLIPPING the images whilst scaling them
marginLeft += 100;
}
To both of the RelativeLayouts I'm adding 10 images. I want both sets of images to be scaled the same, but as the 2nd RL isn't high enough I want those images CLIPPED (the bottom of the image gone).
I've tried all ScaleTypes, but none of them achieve this. The closest is CENTER_CROP, which has the correct scaling, but both the top and bottom are clipped (and, again, I just want the bottom clipped).
Here's a image;
https://imgur.com/a/QLJkm
put this code in viewtreeobserver or you can have custom imageview
Matrix matrix = imageView.getImageMatrix();
float scale;
final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int drawableWidth = drawable.getIntrinsicWidth();
scale = (float) viewWidth / (float) drawableWidth;
matrix.setScale(scale, scale);
setImageMatrix(matrix);

imageView.getWidth(); returns screen instead of bitmap width

I have an imageview that looks like this
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignTop="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginBottom="80dp"
android:layout_marginTop="40dp"
android:onClick="Time"
android:adjustViewBounds="false"
android:src="#drawable/ic_launcher" />
I'm trying to get the width of the image displayed in the imageview by using
ImageView artCover = (ImageView)findViewById(R.id.imageView1);
int coverWidth = artCover.getWidth();
But the width returned is the same as the screen width and not of the image (when the image width is less then the screen width). If I do
int coverHeight = artCover.getHeight();
I get the correct height of the image. How can I get the width of the displayed image?
Your imageview's bitmap is probably scaled and aligned accordingly. You need to take this into account.
// Get rectangle of the bitmap (drawable) drawn in the imageView.
RectF bitmapRect = new RectF();
bitmapRect.right = imageView.getDrawable().getIntrinsicWidth();
bitmapRect.bottom = imageView.getDrawable().getIntrinsicHeight();
// Translate and scale the bitmapRect according to the imageview's scale-type, etc.
Matrix m = imageView.getImageMatrix();
m.mapRect(bitmapRect);
// Get the width of the image as shown on the screen:
int width = bitmapRect.width();
(note that I haven't tried to compile above code, but you'll get the gist of it :-)).
The above code only works when the ImageView has completed its layout.
You have to wait till the View tree has been measured completely which might be even later than onPostResume(). One way to deal with that is:
final ImageView artCover = (ImageView)findViewById(R.id.imageView1);
artCover.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int coverWidth = artCover.getWidth();
}
}
);
You can get image from imageview and will get width the image.
Bitmap bitmap = ((BitmapDrawable)artCover.getDrawable()).getBitmap();<p>
bitmap.getWidth();

Aligning a view to an ImageView in different resolutions

The problem with properly handling multiple screen sizes on Android has been talked all over thousands of times. However I couldn't find a solution to m problem. In a nutshell I need to align my custom progress bar over an imageView. I've got 3 set of drawables for the imageView - ldpi(240x400), mdpi(320x480), hdpi(480x800). I align my custom view in Java with the following code:
//get screen density
float density = getBaseContext().getResources().getDisplayMetrics().density;
//set the progress bar position according to screen density
if ( density == 1.0f)
{
ImageView micImage = ((ImageView) findViewById(R.id.imageViewClk));
Drawable drawing = micImage.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
// Get current dimensions
int width = bitmap.getWidth();
int height = bitmap.getHeight();
LayoutParams params = new LayoutParams((int)(height/13.94), (int)(height/13.94));
params.setMargins((int)(width/2.30), 0, 0, (int)(height/2.75));
params.addRule(RelativeLayout.ALIGN_LEFT,R.id.imageViewClk);
params.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.imageViewClk);
myCustomTwistedProgressBar.setLayoutParams(params);
}else if ( density == 1.5f ){
ImageView micImage = ((ImageView) findViewById(R.id.imageViewClk));
Drawable drawing = micImage.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
int width = bitmap.getWidth();
int height = bitmap.getHeight();
LayoutParams params = new LayoutParams((int)Math.round(height/14.13), (int)Math.round(height/14.13));
params.setMargins((int)Math.round( width/2.27), 0, 0, (int)Math.round(height/2.91));
params.addRule(RelativeLayout.ALIGN_LEFT,R.id.imageViewClk);
params.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.imageViewClk);
myCustomTwistedProgressBar.setLayoutParams(params);
}else if ( density == 0.75f ){
ImageView micImage = ((ImageView) findViewById(R.id.imageViewClk));
Drawable drawing = micImage.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
// Get current dimensions
int width = bitmap.getWidth();
int height = bitmap.getHeight();
LayoutParams params = new LayoutParams((int)(height/14.88), (int)(height/14.88));
params.setMargins((int)(width/2.27), 0, 0, (int)(height/2.69));
params.addRule(RelativeLayout.ALIGN_LEFT,R.id.imageViewClk);
params.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.imageViewClk);
myCustomTwistedProgressBar.setLayoutParams(params);
}
Everything worked fined on different screen sizes however when I tried to check on 480x854 resolution the vertical alignment of the custom view was incorrect. Checked with 480x800 on the same screen size and it again works. I than went for a big jump and checked in GalaxyTab and the horizontal and vertical alignments were wrong. Now my first though was that the bitmap width and height were the one of the image not the actual resized imageview. So I spent a lot of time on trying to get the real size of the imageview and even went for viewTreeObserver but the results were all the same - the correct, unchanged (unscaled?) bitmap size. So being positive that the problem is not here I couldn't get through further. Does anyone have an idea why the alignment is not working correctly?
PS: as for the image view in layout xml file I have 2 configurations for long and notlong but this image has the same description in both:
<ImageView
android:src="#drawable/cloking"
android:id="#+id/imageViewClk"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:layout_above="#+id/imageViewProcess"
android:adjustViewBounds="true"
android:cropToPadding="false"
android:layout_marginTop="60dp"
android:scaleType="fitXY">
</ImageView>
Android will scale the image but it will maintain aspect ratio for the image. You can't control aspect ratio with layout settings (as far as I know). I would solve that problem by choosing few screen ratios that I want to support and making few more resources (images that would have aspect ratios that you support). Code would look like this:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ImageView image = (ImageView) findViewById(R.id.imageViewClk);
if(width/height == aspectRatio1)
{
image.setImageResource(R.id.imageAspect1);
} else if( width/height == aspectRatio2...

Find the position of a bitmap in android imageview when container view scaled centerInside

I have an RelativeLayout that contains a custom ImageView, the scaleType="centerInside", I load in a bitmap (usually smaller than the imageView). How can I get the top/left position of where the bitmap was drawn? I need to be able addView's on top a positions relative to the bitmap.
RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.scroll_scaled, container, false);
ContentImageView image = (ContentImageView) view.findViewById(R.id.base_page);
Bitmap bm = mInterfaceActivity.getPageImage(mPageNumber);
image.setImageBitmap(bm);`
The layout file scrolled_scaled
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:scaleType="centerInside"
android:id="#+id/base_page"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff00ff00"
android:contentDescription="#string/product_page"
android:src="#android:drawable/ic_menu_report_image" >
</ImageView>
</RelativeLayout>
You'll need to do the math yourself using the bounds of the Drawable.
ImageView test = (ImageView) findViewById(R.id.base_page);
Rect bounds = test.getDrawable().getBounds();
int x = (test.getWidth() - bounds.right) / 2;
int y = (test.getHeight() - bounds.bottom) / 2;
First we calculate the space in the View that is not being used by the image. Then since it is centered the extra space is evenly distributed before and after the image so it is draw half of that length into the View.
These numbers are relative to the location of the View but you can add the views X and Y if you need you.
This method returns the bounds of image inside imageView.
/**
* Helper method to get the bounds of image inside the imageView.
*
* #param imageView the imageView.
* #return bounding rectangle of the image.
*/
public static RectF getImageBounds(ImageView imageView) {
RectF bounds = new RectF();
Drawable drawable = imageView.getDrawable();
if (drawable != null) {
imageView.getImageMatrix().mapRect(bounds, new RectF(drawable.getBounds()));
}
return bounds;
}
UPDATE 2: getX and getY will return 0 if you're using unspecified width and height (e.g. wrap_content). Instead of iv.getX() and iv.getY() replace that with the answer to this question: Getting View's coordinates relative to the root layout then add the bounds of the image to those values.
You can do this by adding the ImageView's position to the top left bound of the drawable inside. Something like this:
ImageView iv = (ImageView)findViewById(R.id.image_view);
Drawable d = iv.getDrawable();
Rect bounds = d.getBounds();
int top = iv.getY() + bounds.top;
int left = iv.getX() + bounds.left;
UPDATE: For images that are scaled, you'll have to multiply the top and left coords by the image scale to get more accurate positioning. You can do that like this:
Matrix m = iv.getImageMatrix();
float[] values = new float[9];
m.getValues(values);
float scaleX = values[Matrix.MSCALE_X];
float scaleY = values[Matrix.MSCALE_Y];
Then you'd have to multiply top by scaleY and the left by scaleX.
Ended up with a two part solution, based on the feedback and a bit of retry.
I created the subviews an added them to the RelativeLayout in "approximate"
position, but as View.INVISIBLE.
I super-classed the RelativeLayout ViewGroup and in the onLayout I walked
the list of child views and put them in the "proper" place as I now
had the RelativeLayout self-aware of its expanded size.
Seems clunky, but it works.
Thanks to all for the suggestions, my solution was taking pieces of everyones advice.

Scaling ImageView to device width

In my Android App I have a Activity which show images which have following size 244 x 330.
I want to show those images in full device width.
My layout file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView android:id="#+id/news_image"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_marginLeft="18dip"
android:layout_marginRight="18dip"
android:background="#aaaaaa" />
</LinearLayout>
</ScrollView>
I tried to set the ScaleType of the ImageView but there is no ScalingType which scales the ImageView proportional.
How can I scale the image proportionally to fit the whole screen in landscape mode AND portrait mode?
Basically what I want is something like ScaleType.CENTER_CORP but which also sets the proportional height for the image so I can see all of it and not just a part of the image.
Edit cause I know I'm confusing you with my "weird" questing.
I want to show it to you with a image.
This is what I get at the moment with my layout. I want to fill the whole grey area by scaling the image as big as needed. How can I accomplish that?
When I set the ScaleType to CENTER_CROP I get this
but this is not what I want cause you are not seeing the whole image just a part from the center.
And this is what I want it to be:
I hope this helps you to understand what I'm trying to accomplish.
Anyone knows how to do that?
Edit 2:
It might look weird and little confusing that I'm trying to display a image which is bigger in the height than the screen size but since I'm using a ScrollView in my example layout this should be ok and the user could scroll if he want to see the not displayed area.
Hope this helps to understand what I'm trying to do.
I tried really every ScaleType in my ImageView with fill_parent and wrap_content but no of them worked. I also tried everything what I found on Google but nothing worked for me either so came up with something on my own.
It was clear that the ImageView is not scaling my image like I wanted to be scaled so I had to scale it on my own. After scaling the bitmap I would set the new Bitmap as the image source to the ImageView. This works pretty good and looks very good on the G1 and on the Motorola Milestone 2.
And here is all pieces of my code
Layout:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/news_wrapper">
<ImageView android:id="#+id/news_image"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_marginLeft="18dip"
android:layout_marginRight="18dip"
android:background="#aaaaaa" />
</LinearLayout>
</ScrollView>
Activity
public class ScalingImages extends Activity {
private ImageView imageView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_margin);
this.imageView = (ImageView)findViewById(R.id.news_image);
// The image is coming from resource folder but it could also
// load from the internet or whatever
Drawable drawable = getResources().getDrawable(R.drawable.img);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
// Get scaling factor to fit the max possible width of the ImageView
float scalingFactor = this.getBitmapScalingFactor(bitmap);
// Create a new bitmap with the scaling factor
Bitmap newBitmap = Util.ScaleBitmap(bitmap, scalingFactor);
// Set the bitmap as the ImageView source
this.imageView.setImageBitmap(newBitmap);
}
private float getBitmapScalingFactor(Bitmap bm) {
// Get display width from device
int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
// Get margin to use it for calculating to max width of the ImageView
LinearLayout.LayoutParams layoutParams =
(LinearLayout.LayoutParams)this.imageView.getLayoutParams();
int leftMargin = layoutParams.leftMargin;
int rightMargin = layoutParams.rightMargin;
// Calculate the max width of the imageView
int imageViewWidth = displayWidth - (leftMargin + rightMargin);
// Calculate scaling factor and return it
return ( (float) imageViewWidth / (float) bm.getWidth() );
}
}
Util class
public class Util {
public static Bitmap ScaleBitmap(Bitmap bm, float scalingFactor) {
int scaleHeight = (int) (bm.getHeight() * scalingFactor);
int scaleWidth = (int) (bm.getWidth() * scalingFactor);
return Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
}
}
If there is an better or more accurate way to accomplish the same scaling please let me know because I can't believe that such a trivial thing is so hard to accomplish.
I'm really hoping to see a better way to do this.
Thank you for reading.
the easiest way is to add android:adjustViewBounds="true" to the ImageView and set the scale type to "fitCenter"
Slightly confused on what you're looking for, exactly. If you're scaling to fit the screen, you have three options, two of which are viable if you're keeping proportions. You can use ScaleType fitCenter, which will make the image fit within the bounds proportionally, or you can use centerCrop (which you said you tried), which will stretch the shortest side of the image to fit the container (meaning some will get cropped off on the longer dimension). You can't have it stretch to fit the width AND height without either cropping, or stretching disproportionately.
EDIT: Okay, I think I get your point now. First, I'd set your LinearLayout to wrap_content for the height. Second, in code, here's one way you can do it that I can think of. There's probably also another way you could do it by first getting the screen dimensions, and then doing createScaledBitmap with the new dimensions, and then setting the background resource.
final ImageView newsImage = (ImageView)findViewById(R.id.news_image);
//get details on resolution from the display
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
//going to set what happens as the layout happens
newsImage.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
int oldHeight, oldWidth, newHeight, newWidth;
//we want the new width to be as wide as the screen
newWidth = metrics.widthPixels;
oldHeight = newsImage.getDrawable().getIntrinsicHeight();
oldWidth = newsImage.getDrawable().getIntrinsicWidth();
//keeping the aspect ratio, the new height should be w1/h1 = w2/h2
newHeight = Math.floor((oldHeight * newWidth) / oldWidth);
LinearLayout.LayoutParams params =
(LinearLayout.LayoutParams)newsImage.getLayoutParams();
params.height = newHeight;
params.width = newWidth;
newsImage.setLayoutParams(params);
newsImage.setScaleType(ScaleType.CENTER);
newsImage.invalidate();
newsImage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
}
I googled everywhere and could not find a solution.
Here is what I did, that worked for me and with a scroll view.
XML file:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<ImageView
android:id="#+id/manga_page_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
</ScrollView>
Have you tried setting it programmatically via ImageView.setScaleType()?
setAdjustViewBounds( false ) might help as well.
Edit: sorry, I mis-read the question. Regardless, setAdjustViewBounds() still might help. Never used it though.
I want to show those images in full
device width.
This is simple. You just have the wrong margin settings. Remove these lines and your image will show in full device width:
android:layout_marginLeft="18dip"
android:layout_marginRight="18dip"
I don't see the images anymore and the question is old but just in case someone else finds this and has the same problem. Wouldn't it be better to just get float screenWidth = getResources().getDisplayMetrics().widthPixels and set the ImageView LayoutParamters programmatically to scale the image to screenWidth. Just an idea !!
manage to achieve what I wanted, which hopefully is the same as your aim:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pgviewer);
ImageView PgContainer = (ImageView)findViewById(R.id.imageView1);
String Page = String.valueOf(getIntent().getExtras().getInt("Page"));
try {
PgContainer.setImageBitmap(getBitmapFromAsset(Page));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PgContainer.setScaleType(ScaleType.FIT_CENTER);
PgContainer.scrollTo(0, 0);
PgContainer.setScrollBarStyle(0);
}
then to scale the bitmap:
private Bitmap getBitmapFromAsset(String strName) throws IOException
{
AssetManager assetManager = getAssets();
InputStream istr = assetManager.open(strName+".png");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
float screenWidth = getResources().getDisplayMetrics().widthPixels;
int ih=bitmap.getHeight();
int iw=bitmap.getWidth();
float scalefactor = screenWidth/iw;
//w = 480, h=~
//int newh = bitmap.getHeight()/bitmap.getWidth();
return android.graphics.Bitmap.createScaledBitmap(bitmap, (int)(iw*scalefactor), (int)(ih*scalefactor), true);
//return bitmap;
}
One of the ways to do it is by setting android:adjustViewBounds="true" to the ImageView and set the scale type to "fitCenter" in the xml file.
This should work as expected.
You can also do this programatically by setting ImageView.adjustViewBounds(true) and ImageView.setScaleType(ScaleType.FIT_CENTER).

Categories

Resources