I'm trying to draw an image in a view but having problems trying to maintain the scale of the original image. Basically, I have a small view and I would like to show part of the image in the view. The intention then is to perform a translation on the image so that a different part appears in the view.
No matter what I try, either the image is down-scaled automatically to fit the view or the whole image is viewable. I've tried playing about with the settings on BitmapDrawable, ImageView and Layout to no avail.
Anyone know a good way to achieve this?
Hope This piece of code helps. I have googled it a month ago. It Scrolling performance for the Larger Images.Here whole display size is set as the Height and width of the view. You can change you know. and also can maintain the zoom controls too.
public class LargeImageScroller extends Activity {
// Physical display width and height.
private static int displayWidth = 0;
private static int displayHeight = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// displayWidth and displayHeight will change depending on screen
// orientation. To get these dynamically, we should hook onSizeChanged().
// This simple example uses only landscape mode, so it's ok to get them
// once on startup and use those values throughout.
Display display = ((WindowManager)
getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
displayWidth = display.getWidth();
displayHeight = display.getHeight();
// SampleView constructor must be constructed last as it needs the
// displayWidth and displayHeight we just got.
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private static Bitmap bmLargeImage; //bitmap large enough to be scrolled
private static Rect displayRect = null; //rect we display to
private Rect scrollRect = null; //rect we scroll over our bitmap with
private int scrollRectX = 0; //current left location of scroll rect
private int scrollRectY = 0; //current top location of scroll rect
private float scrollByX = 0; //x amount to scroll by
private float scrollByY = 0; //y amount to scroll by
private float startX = 0; //track x from one ACTION_MOVE to the next
private float startY = 0; //track y from one ACTION_MOVE to the next
public SampleView(Context context) {
super(context);
// Destination rect for our main canvas draw. It never changes.
displayRect = new Rect(0, 0, displayWidth, displayHeight);
// Scroll rect: this will be used to 'scroll around' over the
// bitmap in memory. Initialize as above.
scrollRect = new Rect(0, 0, displayWidth, displayHeight);
// Load a large bitmap into an offscreen area of memory.
bmLargeImage = BitmapFactory.decodeResource(getResources(),
R.drawable.testlargeimage);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Remember our initial down event location.
startX = event.getRawX();
startY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
float x = event.getRawX();
float y = event.getRawY();
// Calculate move update. This will happen many times
// during the course of a single movement gesture.
scrollByX = x - startX; //move update x increment
scrollByY = y - startY; //move update y increment
startX = x; //reset initial values to latest
startY = y;
invalidate(); //force a redraw
break;
}
return true; //done with this event so consume it
}
#Override
protected void onDraw(Canvas canvas) {
// Our move updates are calculated in ACTION_MOVE in the opposite direction
// from how we want to move the scroll rect. Think of this as dragging to
// the left being the same as sliding the scroll rect to the right.
int newScrollRectX = scrollRectX - (int)scrollByX;
int newScrollRectY = scrollRectY - (int)scrollByY;
// Don't scroll off the left or right edges of the bitmap.
if (newScrollRectX < 0)
newScrollRectX = 0;
else if (newScrollRectX > (bmLargeImage.getWidth() - displayWidth))
newScrollRectX = (bmLargeImage.getWidth() - displayWidth);
// Don't scroll off the top or bottom edges of the bitmap.
if (newScrollRectY < 0)
newScrollRectY = 0;
else if (newScrollRectY > (bmLargeImage.getHeight() - displayHeight))
newScrollRectY = (bmLargeImage.getHeight() - displayHeight);
// We have our updated scroll rect coordinates, set them and draw.
scrollRect.set(newScrollRectX, newScrollRectY,
newScrollRectX + displayWidth, newScrollRectY + displayHeight);
Paint paint = new Paint();
canvas.drawBitmap(bmLargeImage, scrollRect, displayRect, paint);
// Reset current scroll coordinates to reflect the latest updates,
// so we can repeat this update process.
scrollRectX = newScrollRectX;
scrollRectY = newScrollRectY;
}
}
}
This probably won't be the most efficient way, but if you're not going to be moving it too much, it'll do.
Treat it like a spritesheet, use Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height) to get the section you want from the original bitmap as its own bitmap, then pass that in instead. Then pass that in rather than the whole bitmap, and it'll only be working with the part you want it to show.
Sounds like you want to have a big ImageView control inside a smaller View (acting like a window), and then move the ImageView control around inside that, so only part of it is visible at a time.
Not exactly sure how you'd do that though, but pretty sure it's possible with AbsoluteLayout and a bit of tinkering.
Related
Based on my previous question of "How to create a BottomBar as StickyBottomCaptureLayout in camera2 Android api?", I created a layout with a StickyBar (SB) which is always locked above/near the system bar. I set the default positions and coordinates of the SB and the other layout in onLayout() (exactly as my answer).
The upper layout is a simple custom DrawView which has an ArrayList of Paths drew by the user. When the device rotates, it recalls onDraw() and calls several times canvas.drawPath(). However, the Paths are redrew with the same coordinates as before but on a different position and layout size. These screenshots demonstrate the actual behavior:
left: portrait - right: landscape
But I want to keep the same coordinates and positions when the orientation changed, like this:
left: same portrait as above - right: landscape with "portrait" coordinates
Locking my activity with android:orientation="portrait" is not the expected solution. I use android:configChanges="orientation" and an OrientationListener to detect the rotation and prevent the total recreation of the Activity.
I tried to set other different positions in onLayout() but obviously, this is not the right way.
I previously tried to transform the multiple Paths like this:
for (Path path : mPathList) {
Matrix matrix = new Matrix();
RectF bounds = new RectF();
path.computeBounds(bounds, true);
// center points to rotate
final float px = bounds.centerX();
final float py = bounds.centerY();
// distance points to move
final float dx; // ?
final float dy; // ?
/** I tried many calculations without success, it's
not worth to paste these dumb calculations here... **/
matrix.postRotate(rotation, px, py); // rotation is 90°, -90° or 0
matrix.postTranslate(dx, dy); // ?
path.transform(matrix);
}
I also tried to rotate the canvas as follows:
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(rotation); // rotation is 90°, -90° or 0
canvas.drawColor(mDrawHelper.getBackgroundViewColor());
for (int i=0; i < mPathList.size(); i++) {
canvas.drawPath(mPathList.get(i), mPaintList.get(i));
}
if (mPath != null && mPaint != null)
canvas.drawPath(mPath, mPaint);
canvas.restore();
}
Anyway, I tried many manipulations but nothing seems to work in this specific case. Does someone have a bright and fabulous idea to share which can lead me in the right direction?
Thanks in advance for the help.
Update: Methodology has been simplified and made easier to follow. The sample app has been updated.
I think I understand what you are trying to do. You want the graphic to maintain its relationship with the StickyCaptureLayout that you have defined. I like the approach using Path and Matrix transformations.
After determining the rotation that the device has undergone, create a Matrix to do the appropriate rotation and rotate about the center of the graphic.
mMatrix.postRotate(rotationDegrees, oldBounds.centerX(), oldBounds.centerY());
Here oldBounds is the bounds of the graphic before location. We will use this to determine margins on the rotated graphic. Go ahead and do the rotation
mPath.transform(mMatrix)
The graphic has been rotated but its position is not correct. It is in the old position but rotated. Create a translation Matrix to move the Path to the appropriate location. The actual computation is dependent upon the rotation. For a 90 degree rotation the computation is
transY = -newBounds.bottom; // move bottom of graphic to top of View
transY += getHeight(); // move to bottom of rotated view
transY -= (getHeight() - oldBounds.right); // finally move up by old right margin
transX = -newBounds.left; // Pull graphic to left of container
transX += getWidth() - oldBounds.bottom; // and pull right for margin
where transY is the Y-translation and transX is the X-translation. oldBounds is the pre-rotation bounds and newBounds is the post-rotation bounds. Important to note here is that getWidth() will give you the "old" View height and getHeight() will give you the old View width.
Here is a sample program that accomplishes what I have described above. A couple of graphics follow showing a 90 degree rotation using this sample app.
Demo app
package com.example.rotatetranslatedemo;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
public class MainActivity extends Activity {
private DrawingView dv;
private Paint mPaint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dv = new DrawingView(this);
setContentView(dv);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.GREEN);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
}
public class DrawingView extends View {
private Bitmap mBitmap;
private Path mPath;
private Paint mBitmapPaint;
Context context;
private Paint paint;
Matrix mMatrix = new Matrix();
RectF oldBounds = new RectF();
RectF newBounds = new RectF();
public DrawingView(Context c) {
super(c);
context = c;
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.MITER);
paint.setStrokeWidth(4f);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
}
#Override
protected void onDraw(Canvas canvas) {
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int rotationDegrees = 0;
float transX = 0;
float transY = 0;
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
// Determine the rotation of the screen.
switch (display.getRotation()) {
case Surface.ROTATION_0:
break;
case Surface.ROTATION_90:
rotationDegrees = 270;
break;
case Surface.ROTATION_180:
rotationDegrees = 180;
break;
case Surface.ROTATION_270:
rotationDegrees = 90;
break;
default:
rotationDegrees = 0;
break;
}
if (mPath == null) { // Just define what we are drawing/moving
mPath = setupGraphic();
}
// Reposition the graphic taking into account the current rotation.
if (rotationDegrees != 0) {
mMatrix.reset();
// Rotate the graphic by its center and in place.
mPath.computeBounds(oldBounds, true);
mMatrix.postRotate(rotationDegrees, oldBounds.centerX(), oldBounds.centerY());
mPath.transform(mMatrix);
// Get the bounds of the rotated graphic
mPath.computeBounds(newBounds, true);
mMatrix.reset();
if (rotationDegrees == 90) {
transY = -newBounds.bottom; // move bottom of graphic to top of View
transY += getHeight(); // move to bottom of rotated view
transY -= (getHeight() - oldBounds.right); // finally move up by old right margin
transX = -newBounds.left; // Pull graphic to left of container
transX += getWidth() - oldBounds.bottom; // and pull right for margin
} else if (rotationDegrees == 270) {
transY = -newBounds.top; // pull top of graphic to the top of View
transY += getHeight() - oldBounds.right; // move down for old right margin
transX = getWidth() - newBounds.right; // Pull to right side of View
transX -= getHeight() - oldBounds.right; // Reestablish right margin
}
mMatrix.postTranslate(transX, transY);
mPath.transform(mMatrix);
}
canvas.drawPath(mPath, mPaint);
}
// Define the graphix that we will draw and move.
private Path setupGraphic() {
int startX;
int startY;
final int border = 20;
Path path;
if (getHeight() > getWidth()) {
startX = getWidth() - border - 1;
startY = getHeight() - border - 1;
} else {
startX = getHeight() - border - 1;
startY = getWidth() - border - 1;
}
startX = startX - 200;
Pt[] myLines = {
new Pt(startX, startY),
new Pt(startX, startY - 500),
new Pt(startX, startY),
new Pt(startX - 100, startY),
new Pt(startX, startY - 500),
new Pt(startX - 50, startY - 400),
new Pt(startX, startY - 500),
new Pt(startX + 50, startY - 400),
new Pt(startX + 200, startY),
new Pt(startX + 200, startY - 500)
};
// Create the final Path
path = new Path();
for (int i = 0; i < myLines.length; i = i + 2) {
path.moveTo(myLines[i].x, myLines[i].y);
path.lineTo(myLines[i + 1].x, myLines[i + 1].y);
}
return path;
}
private static final String TAG = "DrawingView";
}
// Class to hold ordered pair
private class Pt {
float x, y;
Pt(float _x, float _y) {
x = _x;
y = _y;
}
}
}
Portrait
Landscape
Your solution #2 is almost correct. All you need to do is translate your canvas appropriately.
Assuming that rotation is declared as int and may be only 90, -90 or 0, you need to replace this line:
canvas.rotate(rotation); // rotation is 90°, -90° or 0
by the following code:
if (rotation == 90) {
canvas.translate(canvas.getWidth(), 0);
canvas.rotate(90);
} else if (rotation == -90) {
canvas.translate(0, canvas.getHeight());
canvas.rotate(-90);
}
This will work. I can set up a demo project if needed.
Instead of implementing a solution that is very specific to your problem, you can just implement a more generic one. For example a layout that will rotate everything what is inside, which in my opinion is much more elegant.
public class RotatedLayout extends FrameLayout {
public RotatedLayout(Context context) {
super(context);
}
...
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int rotation = 0;
boolean swapDimensions = false;
int translationX = 0;
int translationY = 0;
final Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
switch (display.getRotation()) {
case Surface.ROTATION_0:
rotation = 0;
break;
case Surface.ROTATION_90:
rotation = -90;
swapDimensions = true;
break;
case Surface.ROTATION_180:
rotation = 180;
break;
case Surface.ROTATION_270:
rotation = 90;
swapDimensions = true;
break;
}
if (swapDimensions) {
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int height = MeasureSpec.getSize(heightMeasureSpec);
translationX = (width - height) / 2;
translationY = (height - width) / 2;
final int tmpMeasureSpec = heightMeasureSpec;
heightMeasureSpec = widthMeasureSpec;
widthMeasureSpec = tmpMeasureSpec;
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setTranslationX(translationX);
setTranslationY(translationY);
setRotation(rotation);
}
}
This layout is rather straightforward. It forces itself to be measured with swapped dimensions if displayed in landscape mode. It doesn't care what is inside, so you can put everything there, also a regular interface. After measuring itself (and children) with swapped MeasureSpecs it rotates itself and translates, using view properties, to fit the new position. As a bonus of using view properties - touch events works just fine and this button can be pressed as usual.
In portrait orientation:
Rotated to the left:
Problem with onConfigurationChanged
Although this layout will always draw itself in correct orientation, there must be some event that will cause it to be re-drawn. This may be a problem if you rely only on onConfigurationChanged. In your case Activity can react on changes from landscape to portrait and portrait to landscape. But there is no event sent when switching directly from:
portrait orientation to reverted portrait (if you have the reversed portrait enabled in your AndroidManifest) - marked in blue.
landscape orientation to reversed landscape - marked in red
Please keep in mind that such direct orientation swapping to the reversed orientation is a normal interaction on regular device, it is not something artificial that you can do on emulator only.
There is no standard event sent that will cause views to redraw themselves - no onConfigurationChanged, onMeasure, onLayout, onDraw etc. is invoked.
System just rotates everything for you (without even redrawing it) and it will result in wrong rotation of the view RotatedLayout had no changes to correct it. So be aware that you have to handle this case.
You can see it here in an answered by Dianne Hackborn.
This is simply not a configuration change. There is no notification the
platform provides for when it does this, because it is invisible to the
environment the app is in.
To solve this problem you would have to use SensorManager and register OrientationEventListener to determine when to refresh your view instead of relying on onConfigurationChanged method.
Im using below code to draw line on bitmap canvas while finger touch move... here i posted partial code and it is working fine..
As shown in below image, the black and white bitmap erased on touch drag.. I made canvas transparent so the parent layout background(color image) is getting visible.
I want to know , how much area is erased(like 50% or 60% of bitmap ).. is there any way to find that?
//Erasing paint
mDrawPaint = new Paint();
mDrawPaint.setAntiAlias(true);
mDrawPaint.setDither(true);
mDrawPaint.setStyle(Paint.Style.STROKE);
mDrawPaint.setStrokeJoin(Paint.Join.ROUND);
mDrawPaint.setStrokeCap(Paint.Cap.ROUND);
mDrawPaint.setStrokeWidth(50);
mDrawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
BlurMaskFilter mBlur = new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL);
mDrawPaint.setMaskFilter(mBlur);
private void doDraw(Canvas c) {
c.drawBitmap(mBitmap, 0, 0,null );
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 1;
void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
}
canvas.drawPath(mPath, mDrawPaint ); //Erasing Black and white image
}
void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mDrawPaint);
// kill this so we don't double draw
mPath.reset();
}
Try to use Monte Carlo method to estimate percentage of transparent area. I think it is a fastest and easiest way to do this. Take about 50 (depends on accuracy you need) random pixels on your transparency mask and check their color. Then calc ans = TransparentPixelsCount/TestPixelCount.
It is very hard to calculate square of user's drawings using path coordinates. And it's quite long to iterate over all pixels. So, IMHO Monte Carlo is your choise.
To get an exact (and slow) answer, you need to inspect every pixel and count the number are transparent and divide by the total number of pixels. If your requirements allow for some estimation, it is probably best to sample the image.
You could downsize the image and run and the above procedure on the smaller image. That has the disadvantage that the scaling operation might be going through all the pixels making it slow. I would recommend a grid sampling, it is similar to downsizing, but skips over pixels. Basically, we evenly space x sample points on a grid over the image. Then count the number of sample points that are transparent. The estimate of transparent percentage is the total transparent samples/number of transparent samples. You can get reasonable accuracy (usually within 5%) with a small number, say 100, samples. Here is a code function that implements this method -- bm is the Bitmap and scale is the number of samples per axis, so setting scale = 10 gives 100 total samples (10x10 sampling grid over the image).
static public float percentTransparent(Bitmap bm, int scale) {
final int width = bm.getWidth();
final int height = bm.getHeight();
// size of sample rectangles
final int xStep = width/scale;
final int yStep = height/scale;
// center of the first rectangle
final int xInit = xStep/2;
final int yInit = yStep/2;
// center of the last rectangle
final int xEnd = width - xStep/2;
final int yEnd = height - yStep/2;
int totalTransparent = 0;
for(int x = xInit; x <= xEnd; x += xStep) {
for(int y = yInit; y <= yEnd; y += yStep) {
if (bm.getPixel(x, y) == Color.TRANSPARENT) {
totalTransparent++;
}
}
}
return ((float)totalTransparent)/(scale * scale);
}
For reference, the slow method that would give you the results by counting every pixel is below. It can be used for reference on testing the above estimator.
static public float percentTransparent(Bitmap bm) {
final int width = bm.getWidth();
final int height = bm.getHeight();
int totalTransparent = 0;
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
if (bm.getPixel(x, y) == Color.TRANSPARENT) {
totalTransparent++;
}
}
}
return ((float)totalTransparent)/(width * height);
}
A different approach on this: you can calculate the size of each path using ComputeBounds. Then it should be simple to compare this with the size of your view and decide the % of the drawing.
Jus you need to keep in mind that the path can be drawn over itself, so you need to be careful and handle that in the calculation.
Store all point x and y value in two different sorted sets, one for x value of point and other for y value of point.
The final value of your bound will be point(min_x,min_y) and point(max_x,max_y).
You need to detect the points lying inside the drawn polygon.
Here is the functions which takes array that contains all the drawn point, and second parameter are the points itself i.e. x ,y.
// Return true if the dot { x,y } is within any of the polygons in the list
function pointInPolygons( polygons, dot )
for (i=1, [polygons count] i++)
{
if (pointInPolygon( polygons[i], dot ))
return true
}
return false
end
// Returns true if the dot { x,y } is within the polygon
//defined by points table { {x,y},- --{x,y},{x,y},... }
function pointInPolygon( points, dot )
local i, j = #points, #points
local oddNodes = false
for i=1, #points do
if ((points[i].y < dot.y and points[j].y>=dot.y
or points[j].y< dot.y and points[i].y>=dot.y) and (points[i].x<=dot.x
or points[j].x<=dot.x)) then
if (points[i].x+(dot.y-points[i].y)/(points[j].y-points[i].y)*(points[j].x-points[i].x)<dot.x) then
oddNodes = not oddNodes
end
end
j = i
end
return oddNodes
end
Now I've got this fragment which i want to use setContentView with but so far i cant find how. You can see my case in the code below, im not trying to inflate a layout, im trying to use it with the view called SampleView. So how can I do that?
public class largeImageScroller extends SherlockFragment {
// Physical display width and height.
private static int displayWidth = 0;
private static int displayHeight = 0;
/** Called when the activity is first created. */
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved) {
getActivity();
// displayWidth and displayHeight will change depending on screen
// orientation. To get these dynamically, we should hook onSizeChanged().
// This simple example uses only landscape mode, so it's ok to get them
// once on startup and use those values throughout.
Display display = ((WindowManager)
getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
displayWidth = display.getWidth();
displayHeight = display.getHeight();
// SampleView constructor must be constructed last as it needs the
// displayWidth and displayHeight we just got.
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private static Bitmap bmLargeImage; //bitmap large enough to be scrolled
private static Rect displayRect = null; //rect we display to
private Rect scrollRect = null; //rect we scroll over our bitmap with
private int scrollRectX = 0; //current left location of scroll rect
private int scrollRectY = 0; //current top location of scroll rect
private float scrollByX = 0; //x amount to scroll by
private float scrollByY = 0; //y amount to scroll by
private float startX = 0; //track x from one ACTION_MOVE to the next
private float startY = 0; //track y from one ACTION_MOVE to the next
public SampleView(Context context) {
super(context);
// Destination rect for our main canvas draw. It never changes.
displayRect = new Rect(0, 0, displayWidth, displayHeight);
// Scroll rect: this will be used to 'scroll around' over the
// bitmap in memory. Initialize as above.
scrollRect = new Rect(0, 0, displayWidth, displayHeight);
// Load a large bitmap into an offscreen area of memory.
bmLargeImage = BitmapFactory.decodeResource(getResources(),
R.drawable.ground_floor_b);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Remember our initial down event location.
startX = event.getRawX();
startY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
float x = event.getRawX();
float y = event.getRawY();
// Calculate move update. This will happen many times
// during the course of a single movement gesture.
scrollByX = x - startX; //move update x increment
scrollByY = y - startY; //move update y increment
startX = x; //reset initial values to latest
startY = y;
invalidate(); //force a redraw
break;
}
return true; //done with this event so consume it
}
#Override
protected void onDraw(Canvas canvas) {
// Our move updates are calculated in ACTION_MOVE in the opposite direction
// from how we want to move the scroll rect. Think of this as dragging to
// the left being the same as sliding the scroll rect to the right.
int newScrollRectX = scrollRectX - (int)scrollByX;
int newScrollRectY = scrollRectY - (int)scrollByY;
// Don't scroll off the left or right edges of the bitmap.
if (newScrollRectX < 0)
newScrollRectX = 0;
else if (newScrollRectX > (bmLargeImage.getWidth() - displayWidth))
newScrollRectX = (bmLargeImage.getWidth() - displayWidth);
// Don't scroll off the top or bottom edges of the bitmap.
if (newScrollRectY < 0)
newScrollRectY = 0;
else if (newScrollRectY > (bmLargeImage.getHeight() - displayHeight))
newScrollRectY = (bmLargeImage.getHeight() - displayHeight);
// We have our updated scroll rect coordinates, set them and draw.
scrollRect.set(newScrollRectX, newScrollRectY,
newScrollRectX + displayWidth, newScrollRectY + displayHeight);
Paint paint = new Paint();
canvas.drawBitmap(bmLargeImage, scrollRect, displayRect, paint);
// Reset current scroll coordinates to reflect the latest updates,
// so we can repeat this update process.
scrollRectX = newScrollRectX;
scrollRectY = newScrollRectY;
}
}
}
You dont call setContentView in fragments, in fact you need to return a View from onCreateView.
Try replacing:
setContentView(new SampleView(this));
With this:
return new SampleView(this);
Return the view instance you want to use:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.ads_tab, container, false);
}
Also it's not safe to call getActivity() from onCreateView().
Make sure you call it in or after onActivityCreated(), as at this point your Fragment is fully associated with the Activity. Check Fragment's lifecycle.
Fragments
As explained already, you need to return the view in case of fragments.
But still if you want to use it just like setContentView(), you can do so in following way.
1.Put this code snippet wherever you had to put setContentView()
View v = inflater.inflate(R.layout.activity_home, container, false);
2.Now if you want to access something from xml file, you can do so by using
chart = v.findViewById(R.id.chart);
3. And in the end of OnCreateView() you will have to put
return v;
Full example :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_home, container, false);
chart = v.findViewById(R.id.chart);
return v;
}
In activities we need to set the view using setContentView(R.layout.main)
Where as in fragments we need to override onCreateView() to set the desired view.
I just need to set a high res image, but wants to know if its possible to set it in xml. I want to be able to set it even if it will be bigger than the mobile screen.
EDIT: I want to add a huge image, so the user will have to scroll it. Something like a map, but need to add clickable areas on it and I only know how to do this in xml. That's why I asked to add the image using xml not in java. But if someone can tell me how to add clickable areas in java. That will do it better, since I already have the image but using java and its able to scroll.
EDIT: Heres where I got the code from : Anddev.org I'm using exactly the same code, just with other image.
What are you trying for? In android the resolutions are based on like below -
Screen Support
MultipleResolution
Just read out this. Hope these two links enough for your query.
Have a look at this sample code to see how to scroll an image larger than the screen. It also does bitmap caching to speed up drawing of a complex image, and shows how to respond to long-taps and double-taps at any point on the image.
Ok I'm posting this as an answer, just because it will be easier to post this. (It's not working how I want it to, but I got something) I want to share this so anyone else, who knows how to, can help me out here to find a solution for this one. This is the code
package com.example.largeimagescroller;
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
public class LargeImageScroller extends Activity {
// Physical display width and height.
private static int displayWidth = 0;
private static int displayHeight = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// displayWidth and displayHeight will change depending on screen
// orientation. To get these dynamically, we should hook
// onSizeChanged().
// This simple example uses only landscape mode, so it's ok to get them
// once on startup and use those values throughout.
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
displayWidth = display.getWidth();
displayHeight = display.getHeight();
// SampleView constructor must be constructed last as it needs the
// displayWidth and displayHeight we just got.
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private static Bitmap bmLargeImage; // bitmap large enough to be
// scrolled
private static Rect displayRect = null; // rect we display to
private Rect scrollRect = null; // rect we scroll over our bitmap with
private int scrollRectX = 0; // current left location of scroll rect
private int scrollRectY = 0; // current top location of scroll rect
private float scrollByX = 0; // x amount to scroll by
private float scrollByY = 0; // y amount to scroll by
private float startX = 0; // track x from one ACTION_MOVE to the next
private float startY = 0; // track y from one ACTION_MOVE to the next
public SampleView(Context context) {
super(context);
// Destination rect for our main canvas draw. It never changes.
displayRect = new Rect(0, 0, displayWidth, displayHeight);
// Scroll rect: this will be used to 'scroll around' over the
// bitmap in memory. Initialize as above.
scrollRect = new Rect(0, 0, displayWidth, displayHeight);
// Load a large bitmap into an offscreen area of memory.
bmLargeImage = BitmapFactory.decodeResource(getResources(),
R.drawable.alienware);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//This code define what to do if you touch the x and y coordinates.
float x1 = event.getX();
float y1 = event.getY();
switch (event.getActionMasked()){
case MotionEvent.ACTION_DOWN:
if (x1>150 & x1<200 & y1>400 & y1<500){
Toast.makeText(getContext(), "Touched the coordinates.", Toast.LENGTH_SHORT).show();
}
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Remember our initial down event location.
startX = event.getRawX();
startY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
float x = event.getRawX();
float y = event.getRawY();
// Calculate move update. This will happen many times
// during the course of a single movement gesture.
scrollByX = x - startX; // move update x increment
scrollByY = y - startY; // move update y increment
startX = x; // reset initial values to latest
startY = y;
invalidate(); // force a redraw
break;
}
return true; // done with this event so consume it
}
#Override
protected void onDraw(Canvas canvas) {
// Our move updates are calculated in ACTION_MOVE in the opposite
// direction
// from how we want to move the scroll rect. Think of this as
// dragging to
// the left being the same as sliding the scroll rect to the right.
int newScrollRectX = scrollRectX - (int) scrollByX;
int newScrollRectY = scrollRectY - (int) scrollByY;
// Don't scroll off the left or right edges of the bitmap.
if (newScrollRectX < 0)
newScrollRectX = 0;
else if (newScrollRectX > (bmLargeImage.getWidth() - displayWidth))
newScrollRectX = (bmLargeImage.getWidth() - displayWidth);
// Don't scroll off the top or bottom edges of the bitmap.
if (newScrollRectY < 0)
newScrollRectY = 0;
else if (newScrollRectY > (bmLargeImage.getHeight() - displayHeight))
newScrollRectY = (bmLargeImage.getHeight() - displayHeight);
// We have our updated scroll rect coordinates, set them and draw.
scrollRect.set(newScrollRectX, newScrollRectY, newScrollRectX
+ displayWidth, newScrollRectY + displayHeight);
Paint paint = new Paint();
canvas.drawBitmap(bmLargeImage, scrollRect, displayRect, paint);
// Reset current scroll coordinates to reflect the latest updates,
// so we can repeat this update process.
scrollRectX = newScrollRectX;
scrollRectY = newScrollRectY;
}
}
}
I rec the application in use. (Since touch events don't work with cpu emulators I did it on my phone)
http://www.youtube.com/watch?v=NrszZoDenXE&feature=youtube_gdata
As you can see its taking the touch, but it moves with the scroll rect, so the question will be: How can I do the touch to stay in the image, so it doesn't move with the scrolling rect?
Thanks
So I have an ImageView using a Matrix to scale the Bitmap I'm displaying. I can double-tap to zoom to full-size, and my ScaleAnimation handles animating the zoom-in, it all works fine.
Now I want to double-tap again to zoom out, but when I animate this with ScaleAnimation, the ImageView does not draw the newly exposed areas of the image (as the current viewport shrinks), instead you see the portion of visible image shrinking in. I have tried using ViewGroup.setClipChildren(false), but this only leaves the last-drawn artifacts from the previous frame - leading to an trippy telescoping effect, but not quite what I was after.
I know there are many zoom-related questions, but none cover my situation - specifically animating the zoom-out operation. I do have the mechanics working - ie aside from the zoom-out animation, double-tapping to zoom in and out works fine.
Any suggestions?
In the end I decided to stop using the Animation classes offered by Android, because the ScaleAnimation applies a scale to the ImageView as a whole which then combines with the scale of the ImageView's image Matrix, making it complicated to work with (aside from the clipping issues I was having).
Since all I really need is to animate the changes made to the ImageView's Matrix, I implemented the OnDoubleTapListener (at the end of this post - I leave it as an "exercise to the reader" to add the missing fields and methods - I use a few PointF and Matrix fields to avoid excess garbage creation). Basically the animation itself is implemented by using View.post to keep posting a Runnable that incrementally changes the ImageView's image Matrix:
public boolean onDoubleTap(MotionEvent e) {
final float x = e.getX();
final float y = e.getY();
matrix.reset();
matrix.set(imageView.getImageMatrix());
matrix.getValues(matrixValues);
matrix.invert(inverseMatrix);
doubleTapImagePoint[0] = x;
doubleTapImagePoint[1] = y;
inverseMatrix.mapPoints(doubleTapImagePoint);
final float scale = matrixValues[Matrix.MSCALE_X];
final float targetScale = scale < 1.0f ? 1.0f : calculateFitToScreenScale();
final float finalX;
final float finalY;
// assumption: if targetScale is less than 1, we're zooming out to fit the screen
if (targetScale < 1.0f) {
// scaling the image to fit the screen, we want the resulting image to be centred. We need to take
// into account the shift that is applied to zoom on the tapped point, easiest way is to reuse
// the transformation matrix.
RectF imageBounds = new RectF(imageView.getDrawable().getBounds());
// set up matrix for target
matrix.reset();
matrix.postTranslate(-doubleTapImagePoint[0], -doubleTapImagePoint[1]);
matrix.postScale(targetScale, targetScale);
matrix.mapRect(imageBounds);
finalX = ((imageView.getWidth() - imageBounds.width()) / 2.0f) - imageBounds.left;
finalY = ((imageView.getHeight() - imageBounds.height()) / 2.0f) - imageBounds.top;
}
// else zoom around the double-tap point
else {
finalX = x;
finalY = y;
}
final Interpolator interpolator = new AccelerateDecelerateInterpolator();
final long startTime = System.currentTimeMillis();
final long duration = 800;
imageView.post(new Runnable() {
#Override
public void run() {
float t = (float) (System.currentTimeMillis() - startTime) / duration;
t = t > 1.0f ? 1.0f : t;
float interpolatedRatio = interpolator.getInterpolation(t);
float tempScale = scale + interpolatedRatio * (targetScale - scale);
float tempX = x + interpolatedRatio * (finalX - x);
float tempY = y + interpolatedRatio * (finalY - y);
matrix.reset();
// translate initialPoint to 0,0 before applying zoom
matrix.postTranslate(-doubleTapImagePoint[0], -doubleTapImagePoint[1]);
// zoom
matrix.postScale(tempScale, tempScale);
// translate back to equivalent point
matrix.postTranslate(tempX, tempY);
imageView.setImageMatrix(matrix);
if (t < 1f) {
imageView.post(this);
}
}
});
return false;
}