Why the image gets trimmed off from the top? - image

The code works, but the images get trimmed off from the top. I have tried everything, but I still can't figure it out.
Can someone please take a look at it?
Thanks in advance.
Code:
public class ScalingUtilities {
public static Bitmap decodeResource(Resources res, int resId, int ReqWidth, int ReqHeight, ScalingLogic scalingLogic) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, ReqWidth,
ReqHeight, scalingLogic);
Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options);
return unscaledBitmap;
}
public static Bitmap decode_imagePath_String(String image_path, int ReqWidth, int ReqHeight, ScalingLogic scalingLogic) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image_path, options);
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, ReqWidth,
ReqHeight, scalingLogic);
Bitmap unscaledBitmap = BitmapFactory.decodeFile(image_path, options);
return unscaledBitmap;
}
public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int ReqWidth, int ReqHeight,
ScalingLogic scalingLogic) {
Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
ReqWidth, ReqHeight, scalingLogic);
Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
ReqWidth, ReqHeight, scalingLogic);
Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(),
Config.RGB_565);
Canvas canvas = new Canvas(scaledBitmap);
canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));
return scaledBitmap;
}
public static enum ScalingLogic {
CROP, FIT
}
public static int calculateSampleSize(int srcWidth, int srcHeight, int ReqWidth, int ReqHeight,
ScalingLogic scalingLogic) {
if (scalingLogic == ScalingLogic.FIT) {
final float srcAspect = (float)srcWidth / (float)srcHeight;
final float dstAspect = (float)ReqWidth / (float)ReqHeight;
if (srcAspect > dstAspect) {
return srcWidth / ReqWidth;
} else {
return srcHeight / ReqHeight;
}
} else {
final float srcAspect = (float)srcWidth / (float)srcHeight;
final float dstAspect = (float)ReqWidth / (float)ReqHeight;
if (srcAspect > dstAspect) {
return srcHeight / ReqHeight;
} else {
return srcWidth / ReqWidth;
}
}
}
public static Rect calculateSrcRect(int srcWidth, int srcHeight, int ReqWidth, int ReqHeight,
ScalingLogic scalingLogic) {
if (scalingLogic == ScalingLogic.CROP) {
final float srcAspect = (float)srcWidth / (float)srcHeight;
final float dstAspect = (float)ReqWidth / (float)ReqHeight;
if (srcAspect > dstAspect) {
final int srcRectWidth = (int)(srcHeight * dstAspect);
final int srcRectLeft = (srcWidth - srcRectWidth) / 2;
return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth, srcHeight);
} else {
final int srcRectHeight = (int)(srcWidth / dstAspect);
final int scrRectTop = (int)(srcHeight - srcRectHeight) / 2;
return new Rect(0, scrRectTop, srcWidth, scrRectTop + srcRectHeight);
}
} else {
return new Rect(0, 0, srcWidth, srcHeight);
}
}
public static Rect calculateDstRect(int srcWidth, int srcHeight, int ReqWidth, int ReqHeight,
ScalingLogic scalingLogic) {
if (scalingLogic == ScalingLogic.FIT) {
final float srcAspect = (float)srcWidth / (float)srcHeight;
final float dstAspect = (float)ReqWidth / (float)ReqHeight;
if (srcAspect > dstAspect) {
return new Rect(0, 0, ReqWidth, (int)(ReqWidth / srcAspect));
} else {
return new Rect(0, 0, (int)(ReqHeight * srcAspect), ReqHeight);
}
} else {
return new Rect(0, 0, ReqWidth, ReqHeight);
}
}
}
I very appreciate it...

In calculateSampleSize, you are returning int. Depending on the ratio of your image, this return value may very well be 0 and options.inSampleSize will be 0, so no scaling will take place.
Then the decode will decode with the size values you passed, so cropping will occur. I think that you need to use the density parameters instead. Please take a look at this post

Related

decodeSampledBitmapFromResource what to throw in parameters

Im trying to get my bitmap to fit in my imageview by using the tutorial on android devs but i dont know what to throw in this line imageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
this is my full onActivityResult
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE_CONTENT_RESOLVER) {
if (resultCode == RESULT_OK) {
// Image saved to a generated MediaStore.Images.Media.EXTERNAL_CONTENT_URI
String[] projection = {
MediaStore.MediaColumns._ID,
MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.Images.Media.DATA
};
Cursor c = getContentResolver().query(mPhotoUri, projection, null, null, null);
c.moveToFirst();
String photoFileName = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(photoFileName);
imageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
these are the methods on the android devs
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
}
Im sorry if this is a not a good question but im trying to learn android developing at the moment.
fix it by making the two methods into a class.

ImageManager could not be found in assembly reference Xamarin

Hey I am newbie in xamarin and I working on a sample that requires imaging resizing using this tutorial http://sharpmobilecode.com/android-listviews-reinvented/. However when I add ImageManager. error says It cannot find assembly reference. Its not on System.Drawing also in Android.Drawing. I tried installing in nuget but it yields an error. thanks in advance and have a nice day.
ImageManager is a class that the tutorial implemented as well:
https://github.com/SharpMobileCode/ListViewsReinvented/blob/master/ListViewsReinvented.Droid/ImageManager.cs
So create a class and name it ImageManager, add the code below and change namespace to match yours:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.Content.Res;
using Android.Graphics;
namespace ListViewsReinvented.Droid
{
public class ImageManager : IDisposable
{
private readonly Dictionary<int, Bitmap> _imageCache = new Dictionary<int, Bitmap>();
private Resources _resources;
public ImageManager(Resources resources)
{
_resources = resources;
}
private Task<BitmapFactory.Options> GetBitmapOptionsOfImageAsync(int resourceId)
{
return Task.Run(() => GetBitmapOptionsOfImage(resourceId));
}
private BitmapFactory.Options GetBitmapOptionsOfImage(int resourceId)
{
var options = new BitmapFactory.Options
{
InJustDecodeBounds = true
};
var result = BitmapFactory.DecodeResource(_resources, resourceId, options);
return options;
}
private int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
float height = options.OutHeight;
float width = options.OutWidth;
double inSampleSize = 1D;
if (height > reqHeight || width > reqWidth)
{
int halfHeight = (int)(height / 2);
int halfWidth = (int)(width / 2);
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
{
inSampleSize *= 2;
}
}
return (int)inSampleSize;
}
private Task<Bitmap> LoadScaledDownBitmapForDisplayAsync(BitmapFactory.Options options, int resourceId, int reqWidth, int reqHeight)
{
return Task.Run(() => LoadScaledDownBitmapForDisplay(options, resourceId, reqWidth, reqHeight));
}
private Bitmap LoadScaledDownBitmapForDisplay(BitmapFactory.Options options, int resourceId, int reqWidth, int reqHeight)
{
options.InSampleSize = CalculateInSampleSize(options, reqWidth, reqHeight);
options.InJustDecodeBounds = false;
var bitmap = BitmapFactory.DecodeResource(_resources, resourceId, options);
return bitmap;
}
public Task<Bitmap> GetScaledDownBitmapFromResourceAsync(int resourceId, int requiredWidth, int requiredHeight)
{
return Task.Run(() => GetScaledDownBitmapFromResource(resourceId, requiredWidth, requiredHeight));
}
public Bitmap GetScaledDownBitmapFromResource(int resourceId, int requiredWidth, int requiredHeight)
{
Bitmap bitmap;
if(_imageCache.TryGetValue(resourceId, out bitmap))
{
return bitmap;
}
var options = GetBitmapOptionsOfImage(resourceId);
bitmap = LoadScaledDownBitmapForDisplay(options, resourceId, requiredWidth, requiredHeight);
_imageCache.Add(resourceId, bitmap);
return bitmap;
}
#region IDisposable implementation
public void Dispose()
{
if(_imageCache == null)
return;
foreach(var key in _imageCache.Keys)
{
Bitmap bitmap;
if(_imageCache.TryGetValue(key, out bitmap))
{
Console.WriteLine(String.Format("Recycling bitmap {0} . . .", key));
bitmap.Recycle();
}
}
_imageCache.Clear();
}
#endregion
}
}

XNA SpriteSheet not working

I have added logic to show the Sprite animating but it's simply not showing on the screen. What am I doing wrong?
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
namespace MyXNAGame.Game_Classes
{
public class Player : Sprite
{
private int _frameCount = 6;
private int _frameIndex;
private Rectangle[] _frames;
public float _jumpVelocity = 12f;
public PlayerState _playerState;
public Rectangle BoundingBox
{
get { return new Rectangle {X = (int) Position.X, Y = (int) Position.Y, Height = Texture.Height, Width = Texture.Width}; }
}
public void Initialize()
{
_frames = new Rectangle[_frameCount];
int width = Texture.Width / _frameCount;
for (int i = 0; i < _frameCount; i++)
{
_frames[i] = new Rectangle(i*width, 0, width, Texture.Height);
}
}
public void Load(ContentManager contentManager, string assetName)
{
Texture = contentManager.Load<Texture2D>(assetName);
}
public void Update(GameTime gameTime)
{
while (TouchPanel.IsGestureAvailable)
{
GestureSample gestureSample = TouchPanel.ReadGesture();
if (gestureSample.GestureType == GestureType.Tap)
{
if (_playerState == PlayerState.Running)
{
_playerState = PlayerState.NormalJump;
}
}
if (gestureSample.GestureType == GestureType.Hold)
{
if (_playerState == PlayerState.Running)
{
_playerState = PlayerState.LongJump;
}
}
}
// NormalJump Logic
switch (_playerState)
{
case PlayerState.NormalJump:
Position.Y -= _jumpVelocity;
_jumpVelocity -= 0.5f;
if (_jumpVelocity == 0)
{
_playerState = PlayerState.Falling;
}
break;
case PlayerState.LongJump:
Position.Y -= _jumpVelocity;
_jumpVelocity -= 0.5f;
if (_jumpVelocity == 0)
{
_playerState = PlayerState.Falling;
}
break;
case PlayerState.Falling:
Position.Y += _jumpVelocity;
_jumpVelocity += 0.5f;
break;
case PlayerState.Running:
_frameIndex++;
if (_frameIndex > 5)
{
_frameIndex = 0;
}
break;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, _frames[_frameIndex], Color.White, 0, new Vector2(0, 0), new Vector2(0, 0), SpriteEffects.None, 0);
}
}
}`
Can anyone see the obvious mistake? I am using WP7
I changed the 'Scale' parameter in the Draw() method from new Vector(0,0) to new Vector(1,1) as obviously, having a Scale of 0 will not show anything at all.

BlackBerry - Background bitmap doesn't fit for scrolling page

I have a background bitmap in my Blackberry application screen. Screen has scrolling enabled as i must to have a scroll. The problem which i'm facing is, when i scroll down the page, background bitmap doesn't fit for the scrolled page, rather it shows just plain white background. Do we need to draw the background bitmap for every scrolling page?
My bitmap size is: 360 * 480
Updated code is:
class BGVerticalFieldManager extends VerticalFieldManager {
Bitmap mBgBitmap = null;
int mBgWidth = -1;
int mBgHeight = -1;
int mBgX = -1;
int mBgY = -1;
public BGVerticalFieldManager(Bitmap background) {
super(USE_ALL_WIDTH | USE_ALL_HEIGHT | VERTICAL_SCROLL
| VERTICAL_SCROLLBAR);
mBgBitmap = background;
mBgWidth = mBgBitmap.getWidth();
mBgHeight = mBgBitmap.getHeight();
mBgX = (Display.getWidth() - mBgWidth) >> 1;
mBgY = (Display.getHeight() - mBgHeight) >> 1;
}
protected void paintBackground(Graphics graphics) {
paintBackgroundBitmap(graphics);
invalidate();
}
/*private void paintBackgroundBitmap(Graphics graphics) {
if (null != mBgBitmap) {
int x = mBgX + ((MainScreen)getScreen())
.getMainManager().getHorizontalScroll();
int y = mBgY + ((MainScreen)getScreen())
.getMainManager().getVerticalScroll();
graphics.drawBitmap(x, y, mBgWidth,
mBgHeight, mBgBitmap, 0, 0);
}
} */
private void paintBackgroundBitmap(Graphics graphics) {
if (null != mBgBitmap) {
int x = mBgX
+ getHorizontalScroll();
int y = mBgY
+ getVerticalScroll();
graphics.drawBitmap(x, y, mBgWidth, mBgHeight, mBgBitmap, 0, 0);
}
}
}
CALLING THE ABOVE BACKGROUND BITMAP CODE FROM THE ANOTHER FILE AS BELOW :
public MyFirstScreen ( String label, int screenState, int selectedObj, boolean bUI )
{
super(VERTICAL_SCROLL | VERTICAL_SCROLLBAR); // I must need it ...
appTitle = label;
setTitle(appTitle);
background = Bitmap.getBitmapResource ("HomeBack.png");
add(_container = new BGVerticalFieldManager(background));
..............................
..............................
..............................
}
To get actual scroll position you can use getVerticalScroll():
class BGVerticalFieldManager extends VerticalFieldManager {
Bitmap mBgBitmap = null;
int mBgWidth = -1;
int mBgHeight = -1;
int mBgX = -1;
int mBgY = -1;
public BGVerticalFieldManager(Bitmap background) {
super(USE_ALL_WIDTH | USE_ALL_HEIGHT | VERTICAL_SCROLL
| VERTICAL_SCROLLBAR);
mBgBitmap = background;
mBgWidth = mBgBitmap.getWidth();
mBgHeight = mBgBitmap.getHeight();
mBgX = (Display.getWidth() - mBgWidth) >> 1;
mBgY = (Display.getHeight() - mBgHeight) >> 1;
}
protected void paintBackground(Graphics graphics) {
paintBackgroundBitmap(graphics);
invalidate();
}
private void paintBackgroundBitmap(Graphics graphics) {
if (null != mBgBitmap) {
int x = mBgX
+ getHorizontalScroll();
int y = mBgY
+ getVerticalScroll();
graphics.drawBitmap(x, y, mBgWidth, mBgHeight, mBgBitmap, 0, 0);
}
}
}
alt text http://img693.imageshack.us/img693/6245/9000.jpg
Sample of use:
class Scr extends MainScreen {
private BGVerticalFieldManager mContainer;
public Scr() {
super(NO_VERTICAL_SCROLL);
setTitle("Screen Title");
Bitmap bitmap = Bitmap.getBitmapResource("BoldOEM.jpg");
add(mContainer = new BGVerticalFieldManager(bitmap));
for (int i = 0; i < 100; i++) {
mContainer.add(new LabelField("List item #" + String.valueOf(i)));
mContainer.add(new NullField(FOCUSABLE));
}
}
}
Max Gontar's response is a battery killer;
protected void paintBackground(Graphics graphics) {
paintBackgroundBitmap(graphics);
invalidate();
}
As invalidate() will result in a call to paintBackground(Graphics).

Blackberry - fields layout animation

It's easy to show some animation within one field - BitmapField or Screen:
[Blackberry - background image/animation RIM OS 4.5.0][1]
But what if you need to move fields, not just images?
May be used:
game workflow functionality, like chess, puzzle etc
application user-defined layout, like in Google gadgets
enhanced GUI animation effects
So, I'd like to exchange my expirience in this task, on the other hand, I'd like to know about any others possibilities and suggestions.
This effect may be easily achived with custom layout:
class AnimatedManager extends Manager {
int ANIMATION_NONE = 0;
int ANIMATION_CROSS_FLY = 1;
boolean mAnimationStart = false;
Bitmap mBmpBNormal = Bitmap.getBitmapResource("blue_normal.png");
Bitmap mBmpBFocused = Bitmap.getBitmapResource("blue_focused.png");
Bitmap mBmpRNormal = Bitmap.getBitmapResource("red_normal.png");
Bitmap mBmpRFocused = Bitmap.getBitmapResource("red_focused.png");
Bitmap mBmpYNormal = Bitmap.getBitmapResource("yellow_normal.png");
Bitmap mBmpYFocused = Bitmap.getBitmapResource("yellow_focused.png");
Bitmap mBmpGNormal = Bitmap.getBitmapResource("green_normal.png");
Bitmap mBmpGFocused = Bitmap.getBitmapResource("green_focused.png");
int[] width = null;
int[] height = null;
int[] xPos = null;
int[] yPos = null;
BitmapButtonField mBButton = new BitmapButtonField(mBmpBNormal,
mBmpBFocused);
BitmapButtonField mRButton = new BitmapButtonField(mBmpRNormal,
mBmpRFocused);
BitmapButtonField mYButton = new BitmapButtonField(mBmpYNormal,
mBmpYFocused);
BitmapButtonField mGButton = new BitmapButtonField(mBmpGNormal,
mBmpGFocused);
public AnimatedManager() {
super(USE_ALL_HEIGHT | USE_ALL_WIDTH);
add(mBButton);
add(mRButton);
add(mYButton);
add(mGButton);
width = new int[] { mBButton.getPreferredWidth(),
mRButton.getPreferredWidth(),
mYButton.getPreferredWidth(),
mGButton.getPreferredWidth() };
height = new int[] { mBButton.getPreferredHeight(),
mRButton.getPreferredHeight(),
mYButton.getPreferredHeight(),
mGButton.getPreferredHeight() };
xPos = new int[] { 0, getPreferredWidth() - width[1], 0,
getPreferredWidth() - width[3] };
yPos = new int[] { 0, 0, getPreferredHeight() - height[2],
getPreferredHeight() - height[3] };
Timer timer = new Timer();
timer.schedule(mAnimationTask, 0, 100);
}
TimerTask mAnimationTask = new TimerTask() {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
updateLayout();
};
});
};
};
MenuItem mAnimationMenuItem = new MenuItem("Start", 0, 0) {
public void run() {
mAnimationStart = true;
};
};
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(mAnimationMenuItem);
}
public int getPreferredHeight() {
return Display.getHeight();
}
public int getPreferredWidth() {
return Display.getWidth();
}
protected void sublayout(int width, int height) {
width = getPreferredWidth();
height = getPreferredHeight();
if (getFieldCount() > 3) {
Field first = getField(0);
Field second = getField(1);
Field third = getField(2);
Field fourth = getField(3);
layoutChild(first, this.width[0], this.height[0]);
layoutChild(second, this.width[1], this.height[1]);
layoutChild(third, this.width[2], this.height[2]);
layoutChild(fourth, this.width[3], this.height[3]);
if (mAnimationStart) {
boolean anim1 = performLayoutAnimation(0,
width - this.width[0],
height - this.height[0]);
boolean anim2 = performLayoutAnimation(1, 0,
height - this.height[1]);
boolean anim3 = performLayoutAnimation(2,
width - this.width[2], 0);
boolean anim4 = performLayoutAnimation(3, 0, 0);
mAnimationStart = anim1 || anim2 || anim3 || anim4;
}
setPositionChild(first, xPos[0], yPos[0]);
setPositionChild(second, xPos[1], yPos[1]);
setPositionChild(third, xPos[2], yPos[2]);
setPositionChild(fourth, xPos[3], yPos[3]);
}
setExtent(width, height);
}
boolean performLayoutAnimation(int fieldIndex, int x, int y) {
boolean result = false;
if (xPos[fieldIndex] > x) {
xPos[fieldIndex] -= 2;
result = true;
} else if (xPos[fieldIndex] < x) {
xPos[fieldIndex] += 2;
result = true;
}
if (yPos[fieldIndex] > y) {
yPos[fieldIndex] -= 1;
result = true;
} else if (yPos[fieldIndex] < y) {
yPos[fieldIndex] += 1;
result = true;
}
return result;
}
}
BitmapButtonField class I've used:
class BitmapButtonField extends ButtonField {
Bitmap mNormal;
Bitmap mFocused;
int mWidth;
int mHeight;
public BitmapButtonField(Bitmap normal, Bitmap focused) {
super(CONSUME_CLICK);
mNormal = normal;
mFocused = focused;
mWidth = mNormal.getWidth();
mHeight = mNormal.getHeight();
setMargin(0, 0, 0, 0);
setPadding(0, 0, 0, 0);
setBorder(BorderFactory.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
setBorder(VISUAL_STATE_ACTIVE, BorderFactory
.createSimpleBorder(new XYEdges(0, 0, 0, 0)));
}
protected void paint(Graphics graphics) {
Bitmap bitmap = null;
switch (getVisualState()) {
case VISUAL_STATE_NORMAL:
bitmap = mNormal;
break;
case VISUAL_STATE_FOCUS:
bitmap = mFocused;
break;
case VISUAL_STATE_ACTIVE:
bitmap = mFocused;
break;
default:
bitmap = mNormal;
}
graphics.drawBitmap(0, 0, bitmap.getWidth(), bitmap.getHeight(),
bitmap, 0, 0);
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void layout(int width, int height) {
setExtent(mWidth, mHeight);
}
protected void applyTheme(Graphics arg0, boolean arg1) {
}
}

Resources