Related
I'm scaling the canvas, when I move it, it is going out of the screen.
Screenshot of before translating(i.e., when canvas.onDraw() executes for the first time)
After Move:
I need some condition to say that don't go beyond this point(x-axis - 20).
canvas.save();
int maxX, minX;
minX = /* some condition */;
maxX = /* some condition */;
if (mPosX > maxX)
mPosX = maxX;
if (mPosX < minX)
mPosX = minX;
canvas.translate(mPosX, 0);
canvas.scale(xScaleFactor, yScaleFactor,
px / xScaleFactor + left, py / yScaleFactor + canvas.getClipBounds().top);
paint.setColor(ContextCompat.getColor(getContext(), R.color.green));
canvas.drawRect(20, 20, width, height, paint);
While moving:
#Override
public boolean onTouchEvent(MotionEvent ev) {
mScaleDetector.onTouchEvent(ev);
int eid = ev.getAction();
switch (eid & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
px = ev.getX();
py = ev.getY();
mLastTouchX = px;
mActivePointerId = ev.getPointerId(0);
break;
case MotionEvent.ACTION_MOVE:
if (eid == MotionEvent.ACTION_POINTER_UP || eid == MotionEvent.ACTION_POINTER_DOWN) {
return false;
}
pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)
>> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final float x = ev.getX(pointerIndex);
final float dx = x - mLastTouchX;
mPosX += dx;
invalidate();
mLastTouchX = x;
break;
.......
Kindly help to get some condition which will restrict the rectangle from moving away from the screen. So that the left white space is not created. Every time the canvas invalidates, rectangle should start from position 20 of x-axis.
EDIT:
private Matrix m;
m = new Matrix();
m.mapRect(new RectF(20, 0, mPosX, 0));
// in onDraw()
canvas.save();
m.setTranslate(mPosX, 0);
m.setScale(xScaleFactor, yScaleFactor,
(px + canvas.getClipBounds().left)/ xScaleFactor, (py + canvas.getClipBounds().top)/ yScaleFactor);
canvas.concat(m);
paint.setColor(ContextCompat.getColor(getContext(), R.color.green));
canvas.drawRect(20, 20, width, height, paint);
still it is going out
Am trying out an Android App, where am marking the points where the user does a long press.
For a touch-sensitive image view, I used the most of the code from here:
http://android-developers.blogspot.in/2010/06/making-sense-of-multitouch.html
http://developer.android.com/training/gestures/scale.html
along with some suggestions from various posts in stackoverflow.
This is the code for the touch image view :
public class SimpleImageView extends ImageView implements OnTouchListener,OnGestureListener {
public HashMap<meeCoordinates, Integer> plotPointsMap = new HashMap<meeCoordinates, Integer>();
private float mPosX = 0f;
private float mPosY = 0f;
private boolean didLongPress = false;
private float mLastTouchX;
private float mLastTouchY;
private float magicX;
private float magicY;
private static final int INVALID_POINTER_ID = -1;
Context context;
Canvas canvas;
private GestureDetector gestureScanner;
int deviceWidth, deviceHeight;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;
private int mActivePointerId = INVALID_POINTER_ID;
public SimpleTouchImageView(Context ctx) {
// The ‘active pointer’ is the one currently moving our object.
this(ctx, null, 0);
this.context = ctx;
}
public SimpleTouchImageView(Context ctx, AttributeSet attrs) {
this(ctx, attrs, 0);
this.context = ctx;
}
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
public SimpleTouchImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Create our ScaleGestureDetector
if (!this.isInEditMode()) {
mScaleDetector = new ScaleGestureDetector(context,new ScaleListener());
}
gestureScanner = new GestureDetector(context, this);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (mScaleDetector != null) {
mScaleDetector.onTouchEvent(ev);
}
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
Log.d(TAG, "onTouchEvent MotionEvent.ACTION_DOWN");
final float x = ev.getX();
final float y = ev.getY();
// Set them to the X, Y at the beginning of the touch event
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = ev.getPointerId(0);
// _handler.postDelayed(_longPressed, LONG_PRESS_TIME);
break;
}
case MotionEvent.ACTION_MOVE: {
// _handler.removeCallbacks(_longPressed);
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
if (mScaleDetector != null) {
if (!mScaleDetector.isInProgress()) {
// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
// Move the object
mPosX += dx;
mPosY += dy;
// Remember this touch position for the next move event
mLastTouchX = x;
mLastTouchY = y;
invalidate();
}
}
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP: {
// _handler.removeCallbacks(_longPressed);
mActivePointerId = INVALID_POINTER_ID;
// Calculate the Actual X & Y
Drawable drawable = this.getDrawable();
Rect imageBounds = drawable.getBounds();
int intrinsicHeight = this.getDrawable().getIntrinsicHeight();
int intrinsicWidth = this.getDrawable().getIntrinsicWidth();
int imageOffsetX = (int) (ev.getX() - imageBounds.left);
int imageOffsetY = (int) (ev.getY() - imageBounds.top);
float[] f = newfloat[9];
this.getImageMatrix().getValues(f);
final float scaleX = f[Matrix.MSCALE_X];
final float scaleY = f[Matrix.MSCALE_Y];
final int actualWd = Math.round(intrinsicWidth * mScaleFactor);
final int actualHt = Math.round(intrinsicHeight * mScaleFactor);
// CALCULATE THE X,Y COORDINATES CORRESPONDING TO THE POINT OF TOUCH
// IN THE ACTUAL IMAGE,
magicX = ((ev.getX() + (-1 * mPosX)) / mScaleFactor);
magicY = ((ev.getY() + (-1 * mPosY)) / mScaleFactor);
mLastTouchX = ev.getX();
mLastTouchY = ev.getY();
if (didLongPress == true) {
// STORE THE Point where user did long press IN AN ARRAY
plotPointsMap.put ( coordinates, marker );
invalidate();
didLongPress = false;
}
break;
}
case MotionEvent.ACTION_CANCEL: {
// _handler.removeCallbacks(_longPressed);
Log.d(TAG, "onTouchEvent MotionEvent.ACTION_CANCEL");
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
// _handler.removeCallbacks(_longPressed);
Log.d(TAG, "onTouchEvent MotionEvent.ACTION_POINTER_UP");
break;
}
}
// return true;
return gestureScanner.onTouchEvent(ev);
}
/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
}
#Override
public void onDraw(Canvas canvas) {
WindowManager wm = (WindowManager) this.context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
deviceWidth = metrics.widthPixels;
deviceHeight = metrics.heightPixels;
canvas.drawRect(0, 0, getWidth(), getHeight(), backgroundPaint);
if (this.getDrawable() != null) {
canvas.save();
canvas.translate(mPosX, mPosY);
Matrix matrix = new Matrix();
matrix.postScale(mScaleFactor, mScaleFactor, pivotPointX,pivotPointY);
canvas.drawBitmap(((BitmapDrawable) this.getDrawable()).getBitmap(), matrix,null);
// ---add the marker---
if ((plotPointsMap != null) && (plotPointsMap.size() > 0)) {
for (int index = 0; index < plotPointsMap.size(); index++) {
Set<MyCoordinates> setCoordinates = plotPointsMap.keySet();
if ((setCoordinates != null) && (setCoordinates.size() > 0)) {
Iterator<MyCoordinates> setIterator =setCoordinates.iterator();
if (setIterator != null) {
while (setIterator.hasNext()) {
MyCoordinates coordinates = setIterator.next();
int resource = plotPointsMap.get(coordinates).intValue();
int resourceId = R.drawable.location_marker;
Bitmap marker = BitmapFactory.decodeResource(getResources(), resourceId);
float xCoordinate = coordinates.getCoordinateX();
float yCoordinate = coordinates.getCoordinateY();
canvas.drawBitmap(marker, xCoordinate * mScaleFactor, yCoordinate * mScaleFactor, null);
}
}
}
}
}
canvas.restore();
}
}
#Override
public void setImageDrawable(Drawable drawable) {
// Constrain to given size but keep aspect ratio
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
mLastTouchX = mPosX = 0;
mLastTouchY = mPosY = 0;
mScaleFactor = Math.min((float) getLayoutParams().width/ width, (float) getLayoutParams().height/ height);
pivotPointX = ((float) getLayoutParams().width - (int) (width * mScaleFactor)) / 2;
pivotPointY = ((float) getLayoutParams().height - (int) (height * mScaleFactor)) / 2;
super.setImageDrawable(drawable);
}
float pivotPointX = 0f;
float pivotPointY = 0f;
...
...
}
The Issue
Let's keep aside scaling for now. Say, the image is loaded in its actual size. The point where the user touches is recorded correctly. Say, if the user touches at (120, 50) with x=120 and y=50, then it detects correctly as (120, 50). Am storing the points in an array and re-drawing a marker at each of the points in
public void onDraw(Canvas canvas)
The problem is that when the marker is drawn at the point (am printing it within onDraw(canvas)), the marker is drawn about 30px away from the actual point. i.e. if actual (x,y) is (120,50), then the marker image is drawn at about (150,80). Always there is this 30px difference. Why is this? Am breaking my head on this since the last two weeks in vain. Can someone please help?
here is an image showing the touch point in blue (over the letter 'S' in 'U.S.'), and you can see that the black marker is being drawn off the touch point :
EDIT
When I pan the image, inverse.mapPoints() doesn't account for the offset of the image away from the screen.
For example, here is the image when the App begins, this is the image loaded
and when the user pans, the image might go to the left of the screen-edge as below:
In such a case, inverse.mapPoints() only returns the value from the edge of the screen, but I want the value from the edge of the original image. How do I do it?
I tried googl'ing and tried few things given in stackoverflow (like getTop(), and getLocationOnscreen()) but in vain.
can you help?
1 use getImageMatrix()
2 invert it - invert()
3 use inverted.mapPoints()
I'm developing an application in which I'm pasting images, doing drawing and painting on canvas. This app can also Scale up/down the canvas or drag it to different location.
My problem is: I can't get the correct canvas coordinates after scaling or dragging the canvas. I want to draw finger paint after the canvas is scaled or dragged but unable to retrieve the right place where i've touched..:(
Also I'm new bee. Here is the code.
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
//canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor, super.getWidth() * 0.5f,
super.getHeight() * 0.5f);
mIcon.draw(canvas);
for (Path path : listPath) {
canvas.drawPath(path, paint);
}
canvas.restore();
}
public TouchExampleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
// Only move if the ScaleGestureDetector isn't processing a gesture.
if (!mScaleDetector.isInProgress()) {
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
invalidate();
}
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
break;
}
}
float objectNewX,objectNewY;
if (mScaleFactor >= 1) {
objectNewX = ev.getX() + (ev.getX() - super.getWidth() * 0.5f) * (mScaleFactor - 1);
objectNewY = ev.getY() + (ev.getY() - super.getHeight() * 0.5f) * (mScaleFactor - 1);
} else {
objectNewX = ev.getX() - (ev.getX() - super.getWidth() * 0.5f) * (1 - mScaleFactor);
objectNewY = ev.getY() - (ev.getY() - super.getHeight() * 0.5f) * (1 - mScaleFactor);
}
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
path = new Path();
path.moveTo(objectNewX,objectNewY);
path.lineTo(objectNewX,objectNewY);
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
path.lineTo(objectNewX,objectNewY);
listPath.add(path);
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
path.lineTo(objectNewX,objectNewY);
listPath.add(path);
}
return true;
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
invalidate();
return true;
}
}
Done it finally by myself.
Draw everything by applying this formula to (px,py) coordinates:
float px = ev.getX() / mScaleFactor + rect.left;
float py = ev.getY() / mScaleFactor + rect.top;
rect = canvas.getClipBounds();
//Get them in on Draw function and apply above formula before drawing
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
clipBounds_canvas = canvas.getClipBounds();
/////Do whatever you want to do..!!!
};
#Override
public boolean onTouchEvent(MotionEvent ev) {
int x = ev.getX() / zoomFactor + clipBounds_canvas.left;
int y = ev.getY() / zoomFactor + clipBounds_canvas.top;
//Use the above two values insted of ev.getX() and ev.getY();
}
Hope this will help.
How can I write text on an image and then save it in Android?
Basically I want to let user write something on the images which my camera app will click for them. I can write and show it to them using the onDraw method on the preview of the camera. But after the user has clicked the picture I want to write the text over the picture and then save it.
You can put an EditText and write into it, and after writing, you first convert it to Bitmap like:
Bitmap bmp = Bitmap.createBitmap(mEditText.getDrawingCache());
Now you can add created image bmp to your original image like this:
Call: Bitmap combined = combineImages(bgBitmap,bmp);
public Bitmap combineImages(Bitmap background, Bitmap foreground) {
int width = 0, height = 0;
Bitmap cs;
width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
background = Bitmap.createScaledBitmap(background, width, height, true);
comboImage.drawBitmap(background, 0, 0, null);
comboImage.drawBitmap(foreground, matrix, null);
return cs;
}
You have to implement a canvas that allows the user to draw on it and then set the background of that canvas to that particular image. This is just a guess but its somewhere there abouts.
Lets help you..
First of all you must have to use canvas for drawing. Make a custom view which extends ImageView. Here is the helping code for onDraw function..:
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
mIcon.setBounds(0, 0, mIcon.getMinimumWidth(),
mIcon.getMinimumHeight());
canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor, canvas.getWidth() * 0.5f,
canvas.getWidth() * 0.5f);
mIcon.draw(canvas);
rect = canvas.getClipBounds();
for (Path path : listPath) {
canvas.drawPath(path, paint);
}
}
Now for onTouch:
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
if (drawing) {
startPoint = new Point((int) ev.getX(), (int) ev.getY());
path = new Path();
float x = ev.getX() / mScaleFactor + rect.left;
float y = ev.getY() / mScaleFactor + rect.top;
path.moveTo(x, y);
path.lineTo(x, y);
mLastTouchX_1 = x;
mLastTouchY_1 = y;
}
else {
final float x = ev.getX();
final float y = ev.getY();
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = ev.getPointerId(0);
}
break;
}
case MotionEvent.ACTION_MOVE: {
if (drawing) {
float x = ev.getX() / mScaleFactor + rect.left;
float y = ev.getY() / mScaleFactor + rect.top;
path.moveTo(mLastTouchX_1, mLastTouchY_1);
path.lineTo(x, y);
mLastTouchX_1 = x;
mLastTouchY_1 = y;
}
else {
final int pointerIndex = ev
.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
// Only move if the ScaleGestureDetector isn't processing a
// gesture.
if (!mScaleDetector.isInProgress()) {
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
invalidate();
}
mLastTouchX = x;
mLastTouchY = y;
}
break;
}
case MotionEvent.ACTION_UP: {
path_helper_1 = new Path();
path_helper_2 = new Path();
endPoint = new Point((int) ev.getX(), (int) ev.getY());
int left, top, right, bottom;
left = endPoint.x - 10;
top = endPoint.y - 10;
right = endPoint.x + ((endPoint.y / 2));
bottom = endPoint.x + ((endPoint.y / 2));
float dx, dy;
dx = endPoint.x - startPoint.x;
dy = endPoint.y - startPoint.y;
dx = dx * -1;
dy = dy * -1;
// dx = dy = 100;
double cos = 0.866 * .1;
double sin = 0.500 * .1;
PointF end1 = new PointF((float) (endPoint.x + (dx * cos + dy
* -sin)), (float) (endPoint.y + (dx * sin + dy * cos)));
PointF end2 = new PointF((float) (endPoint.x + (dx * cos + dy
* sin)), (float) (endPoint.y + (dx * -sin + dy * cos)));
// path.moveTo(endPoint.x, endPoint.y);
//
// path.lineTo(endPoint.x, endPoint.y);
//
// path.lineTo(end1.x, end1.y);
//
// path.moveTo(endPoint.x, endPoint.y);
//
// path.lineTo(end2.x, end2.y);
//
//
// listPath.add(path);
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
break;
}
}
invalidate();
return true;
}
Also make a private class if you want to implement zooming functionality like this:
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
if (zoom) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
}
invalidate();
return true;
}
}
}
Take the idea from above code and make changes according to your requirements.
NOTE Above code implements Drawing And Zooming functionality. If you want to add text over images then like Path drawing you can also draw text on canvas using canvas.drawText. Make an arraylist if you want multiple text overs image.
Add text on bitmap :
public Bitmap drawTextToBitmap(Context gContext,
int gResId,
String gText) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap =
BitmapFactory.decodeResource(resources, gResId);
android.graphics.Bitmap.Config bitmapConfig =
bitmap.getConfig();
// set default bitmap config if none
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// resource bitmaps are imutable,
// so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
// new antialised Paint
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.rgb(61, 61, 61));
// text size in pixels
paint.setTextSize((int) (14 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
int x = (bitmap.getWidth() - bounds.width())/2;
int y = (bitmap.getHeight() + bounds.height())/2;
canvas.drawText(gText, x, y, paint);
return bitmap;
}
Source : http://www.skoumal.net/en/android-how-draw-text-bitmap/
Add multi line text on bitmap :
public Bitmap drawMultilineTextToBitmap(Context gContext,
int gResId,
String gText) {
// prepare canvas
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
// set default bitmap config if none
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// resource bitmaps are imutable,
// so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
// new antialiased Paint
TextPaint paint=new TextPaint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.rgb(61, 61, 61));
// text size in pixels
paint.setTextSize((int) (14 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
// set text width to canvas width minus 16dp padding
int textWidth = canvas.getWidth() - (int) (16 * scale);
// init StaticLayout for text
StaticLayout textLayout = new StaticLayout(
gText, paint, textWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
// get height of multiline text
int textHeight = textLayout.getHeight();
// get position of text's top left corner
float x = (bitmap.getWidth() - textWidth)/2;
float y = (bitmap.getHeight() - textHeight)/2;
// draw text to the Canvas center
canvas.save();
canvas.translate(x, y);
textLayout.draw(canvas);
canvas.restore();
return bitmap;
}
Source : http://www.skoumal.net/en/android-drawing-multiline-text-on-bitmap/
anyone knows how to zoom paint view with image correctly?
At following code, I used canvas zoom in order to zoom paint view with image including using setImageMatrix().
But problem arised, that is entire screen became to zoom in/out but not paint view and image only.
So If anyone knows this issue, reply plz.
PaintScreen.java
public class PaintScreen extends Activity implements ColorPickerDialog.OnColorChangedListener{
Context mContext;
private Paint mPaint;
MaskFilter mEmboss;
MaskFilter mBlur;
private ImageView mImageView;
private LinearLayout mPaintBaseLayout;
private FrameLayout mTouchBaseLayout;
private PaintView mPaintView;
private int[] mPixels;
private Bitmap mBitmapImage;
private DisplayMetrics mDisplayMetrics = new DisplayMetrics();
MultiTouchListener multiTouchLitener = new MultiTouchListener(this);
private static final String TAG = "Touch";
// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
Matrix savedMatrix2 = new Matrix();
private int WIDTH = 0;
private int HEIGHT = 1;
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int POINT2 = 2;
static final int ZOOM = 3;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
float newDist;
float distanceOffset = 50f;
float minOffset = 50f;
float maxOffset = 10000f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paint_mode1_paint);
this.initialize();
this.PaintSet();
}
private void initialize()
{
mPaintBaseLayout = (LinearLayout) findViewById(R.id.paint_paint_base_layout);
mTouchBaseLayout = (FrameLayout) findViewById(R.id.paint_touch_base_layout);
mContext = this;
mPaint = new Paint();
mPaintView = new PaintView(mContext);
mPaintView.setBackgroundColor(Color.TRANSPARENT);
mPaintBaseLayout.addView(mPaintView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mPaintBaseLayout.setBackgroundColor(Color.TRANSPARENT);
mPaintView.setScaleType(ScaleType.MATRIX);
mPaintView.setMPaint(mPaint);
Intent intent = getIntent();
Bundle itstr = intent.getExtras();
String imagePath = itstr.getString("image_path");
Drawable d = Drawable.createFromPath(imagePath);
mPaintView.setBackgroundDrawable(d);
mPaintView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
dumpEvent(event);
PaintView view = (PaintView) v;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
start.set(event.getX(), event.getY());
savedMatrix.set(matrix);
midPoint(mid, event);
mode = POINT2;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
distanceOffset = minOffset;
break;
case MotionEvent.ACTION_MOVE:
if (mode == POINT2)
{
newDist = spacing(event);
if (newDist - oldDist > 5f
|| newDist - oldDist < -5f) {
mode = ZOOM;
} else {
start.set(event.getX(), event.getY());
mode = DRAG;
}
} else
if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x,
event.getY() - start.y);
}
else if (mode == ZOOM) {
newDist = spacing(event);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
} else {
view.onTouchEvent(event);
}
break;
}
matrixTurning(matrix, view);
view.setImageMatrix(matrix);
view.cMatrix(matrix);
return true;
}
});
}
/** Show an event in the LogCat view, for debugging */
private static void dumpEvent(MotionEvent event) {
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
Log.d(TAG, sb.toString());
}
/** Determine the space between the first two fingers */
private static float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
private static void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
private void matrixTurning(Matrix matrix, ImageView view){
float[] value = new float[9];
matrix.getValues(value);
float[] savedValue = new float[9];
savedMatrix2.getValues(savedValue);
// view size
int width = view.getWidth();
int height = view.getHeight();
//image size
Drawable d = view.getDrawable();
if(d == null) return;
int imageWidth = d.getIntrinsicWidth();
int imageHeight = d.getIntrinsicHeight();
int scaleWidth = (int)(imageWidth*value[0]);
int scaleHeight = (int)(imageHeight*value[0]);
if(value[2] < width - scaleWidth) value[2] = width - scaleWidth;
if(value[5] < height - scaleHeight) value[5] = height - scaleHeight;
if(value[2] > 0) value[2] = 0;
if(value[5] > 0) value[5] = 0;
if(value[0] > 10 || value[4] > 10){
value[0] = savedValue[0];
value[4] = savedValue[4];
value[2] = savedValue[2];
value[5] = savedValue[5];
}
if(imageWidth > width || imageHeight > height){
if(scaleWidth < width && scaleHeight < height){
int target = WIDTH;
if(imageWidth < imageHeight) target = HEIGHT;
if(target == WIDTH) value[0] = value[4] = (float)width/imageWidth;
if(target == HEIGHT) value[0] = value[4] = (float)height/imageHeight;
scaleWidth = (int)(imageWidth*value[0]);
scaleHeight = (int)(imageHeight*value[4]);
if(scaleWidth == width) value[0] = value[4] = (float)width/imageWidth;
if(scaleHeight == height) value[0] = value[4] = (float)height/imageHeight;
}
}else{
if(value[0] < 1) value[0] = 1;
if(value[4] < 1) value[4] = 1;
}
scaleWidth = (int)(imageWidth*value[0]);
scaleHeight = (int)(imageHeight*value[4]);
if(scaleWidth < width){
value[2] = (float)width/2-(float)scaleWidth/2;
}
if(scaleHeight < height){
value[5] = (float)height/2-(float)scaleHeight/2;
}
matrix.setValues(value);
savedMatrix2.set(matrix);
}
public void PaintSet(){
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(24);
getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(24, BlurMaskFilter.Blur.NORMAL);
}
public void colorChanged(int color) {
mPaint.setColor(color);
}
}
PaintView.java
public class PaintView extends ImageView {
private Context mContext;
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private Bitmap testBitmap;
private Canvas mCanvas;
private Canvas tCanvas;
private Path mPath;
private Paint mBitmapPaint;
// onDraw
private Paint mPaint;
private MaskFilter mEmboss;
private MaskFilter mBlur;
// onTouch
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
public PaintView(Context context) {
this(context, null);
// TODO Auto-generated constructor stub
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
mContext = context;
mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
//mCanvas = new Canvas(mBitmap);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
//canvas.drawColor(0xFFAAAAAA);
super.onDraw(canvas);
mCanvas = canvas;
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
public void setMPaint(Paint paint) {
mPaint = paint;
}
private void touchStart(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(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;
}
}
private void touchUp() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
Log.d("PaintView", "ev ->" + event.getAction());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touchUp();
invalidate();
break;
}
return true;
}
public void cMatrix(Matrix matrix) {
mCanvas.setMatrix(matrix);
}
}
#Override
protected void onDraw(Canvas canvas) {
//canvas.drawColor(0xFFAAAAAA);
super.onDraw(canvas);
mCanvas = canvas;
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
In this method you write, mCanvas = canvas; instead of this write, canvas = mCanvas.
Hello try with below code for paint and capture new bitmap with pain image.first zoom in/out image and on button click draw paint.then click on done button for save your final merge bitmap.Hop its helpful to you.
public class PaintScreen extends Activity {
Context mContext;
private Paint mPaint;
MaskFilter mEmboss;
MaskFilter mBlur;
private LinearLayout mPaintBaseLayout, mPaintBaseLayout2;
private PaintView mPaintView;
// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix matrix1 = new Matrix();
Matrix savedMatrix = new Matrix();
Matrix savedMatrix2 = new Matrix();
Matrix dmMtrx = new Matrix();
private int WIDTH = 0;
private int HEIGHT = 1;
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int POINT2 = 2;
static final int ZOOM = 3;
int mode = NONE;
private static final float MIN_ZOOM = 0.0f;
private static final float MAX_ZOOM = 1.0f;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
float newDist;
float distanceOffset = 50f;
float minOffset = 50f;
float maxOffset = 10000f;
private boolean falg = true;
private int startval = 0;
Bitmap newbm;
private float finalscale;
Bitmap bm;
private float scaledImageOffsetX;
private float scaledImageOffsetY;
ImageView imageView;
ProgressDialog dialog;
private float[] matrixValues;
Bitmap temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_main);
this.initialize();
this.PaintSet();
imageView = (ImageView) findViewById(R.id.imageview1);
Button button = (Button) findViewById(R.id.btnzoom);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (falg) {
getFlag(false);
} else {
getFlag(true);
}
}
});
Button btnset = (Button) findViewById(R.id.btnset);
btnset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startval = 1;
mPaintBaseLayout.setDrawingCacheEnabled(true);
/*newbm = Bitmap.createBitmap(bm.getWidth(),
bm.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newbm);
mPaintBaseLayout.draw(canvas);*/
// mPaintView.clear();
/*
mPaintView.setScaleType(ScaleType.MATRIX);
mPaintView.setMPaint(mPaint);
mPaintView.setImageBitmap(newbm);*/
imageView.setVisibility(View.VISIBLE);
mPaintBaseLayout.setVisibility(View.GONE);
new SaveImageAsynk().execute();
}
});
imageView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix1);
start.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
start.set(event.getX(), event.getY());
savedMatrix.set(matrix1);
midPoint(mid, event);
// mode = POINT2;
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:
mode = NONE;
distanceOffset = minOffset;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
distanceOffset = minOffset;
break;
case MotionEvent.ACTION_MOVE:
if (mode == POINT2) {
newDist = spacing(event);
if (newDist - oldDist > 5f
|| newDist - oldDist < -5f) {
mode = ZOOM;
} else {
start.set(event.getX(), event.getY());
mode = DRAG;
}
} else if (mode == DRAG) {
matrix1.set(savedMatrix);
matrix1.postTranslate(event.getX() - start.x,
event.getY() - start.y);
} else if (mode == ZOOM) {
newDist = spacing(event);
if (newDist > 10f) {
matrix1.set(savedMatrix);
float scale = newDist / oldDist;
matrix1.postScale(scale, scale, mid.x,
mid.y);
finalscale = scale;
}
}
break;
}
view.setImageMatrix(matrix1);
// matrixTurning(matrix1, view);
return true; // indicate event was handled
}
});
}
class SaveImageAsynk extends AsyncTask<String, String, String>{
Bitmap tempBm;
#Override
protected String doInBackground(String... params) {
temp = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, false);
newbm = Bitmap.createBitmap(mPaintBaseLayout.getWidth(),
mPaintBaseLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newbm);
mPaintBaseLayout.draw(canvas);
tempBm = combineImages(newbm, temp);
if (newbm != null) {
newbm = null;
}
if (temp != null) {
temp = null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
imageView.setImageBitmap(tempBm);
try {
dialog.dismiss();
if (dialog != null) {
dialog = null;
}
} catch (Exception e) {
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(PaintScreen.this);
dialog.setMessage("Loading...");
dialog.show();
}
}
public Bitmap combineImages(Bitmap c, Bitmap s) {
Bitmap cs = null;
int width, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
Log.e("hw :", "X = "+width + " Y = "+height);
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(s,new Matrix(), null);
comboImage.drawBitmap(c,Math.abs(scaledImageOffsetX),Math.abs(scaledImageOffsetY), null);
return cs;
}
private void initialize() {
mPaintBaseLayout = (LinearLayout) findViewById(R.id.paint_paint_base_layout);
mPaintBaseLayout2 = (LinearLayout) findViewById(R.id.paint_paint_base_layout2);
mContext = this;
mPaint = new Paint();
mPaintView = new PaintView(mContext);
mPaintView.setBackgroundColor(Color.TRANSPARENT);
mPaintBaseLayout.addView(mPaintView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mPaintBaseLayout.setBackgroundColor(Color.TRANSPARENT);
// mPaintView.setScaleType(ScaleType.FIT_XY);
mPaintView.setAdjustViewBounds(true);
mPaintView.setMPaint(mPaint);
bm = BitmapFactory.decodeResource(getResources(), R.drawable.nat);
mPaintView.setImageBitmap(bm);
mPaintView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
PaintView view = (PaintView) v;
view.setScaleType(ImageView.ScaleType.MATRIX);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (falg) {
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
} else {
view.onTouchEvent(event);
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (falg) {
oldDist = spacing(event);
if (oldDist > 10f) {
start.set(event.getX(), event.getY());
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
}
break;
case MotionEvent.ACTION_UP:
if (falg) {
mode = NONE;
distanceOffset = minOffset;
}
case MotionEvent.ACTION_POINTER_UP:
if (falg) {
mode = NONE;
distanceOffset = minOffset;
}
break;
case MotionEvent.ACTION_MOVE:
if (falg) {
if (mode == POINT2) {
newDist = spacing(event);
if (newDist - oldDist > 5f
|| newDist - oldDist < -5f) {
mode = ZOOM;
} else {
start.set(event.getX(), event.getY());
mode = DRAG;
}
} else if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x,
event.getY() - start.y);
} else if (mode == ZOOM) {
newDist = spacing(event);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
finalscale = scale;
}
}
} else {
view.onTouchEvent(event);
}
break;
}
limitZoom(matrix);
view.setImageMatrix(matrix);
matrixTurning(matrix, view);
RectF r = new RectF();
matrix.mapRect(r);
scaledImageOffsetX = r.left;
scaledImageOffsetY = r.top;
return true;
}
});
}
private void limitZoom(Matrix m) {
float[] values = new float[9];
m.getValues(values);
float scaleX = values[Matrix.MSCALE_X];
float scaleY = values[Matrix.MSCALE_Y];
if(scaleX > MAX_ZOOM) {
scaleX = MAX_ZOOM;
} else if(scaleX < MIN_ZOOM) {
scaleX = MIN_ZOOM;
}
if(scaleY > MAX_ZOOM) {
scaleY = MAX_ZOOM;
} else if(scaleY < MIN_ZOOM) {
scaleY = MIN_ZOOM;
}
values[Matrix.MSCALE_X] = scaleX;
values[Matrix.MSCALE_Y] = scaleY;
m.setValues(values);
}
public boolean getFlag(boolean b) {
return falg = b;
}
/** Determine the space between the first two fingers */
private static float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
private static void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
private void matrixTurning(Matrix matrix, ImageView view) {
float[] value = new float[9];
matrix.getValues(value);
float[] savedValue = new float[9];
savedMatrix2.getValues(savedValue);
// view size
int width = view.getWidth();
int height = view.getHeight();
// image size
Drawable d = view.getDrawable();
if (d == null)
return;
int imageWidth = d.getIntrinsicWidth();
int imageHeight = d.getIntrinsicHeight();
int scaleWidth = (int) (imageWidth * value[0]);
int scaleHeight = (int) (imageHeight * value[0]);
if (value[2] < width - scaleWidth)
value[2] = width - scaleWidth;
if (value[5] < height - scaleHeight)
value[5] = height - scaleHeight;
if (value[2] > 0)
value[2] = 0;
if (value[5] > 0)
value[5] = 0;
if (value[0] > 10 || value[4] > 10) {
value[0] = savedValue[0];
value[4] = savedValue[4];
value[2] = savedValue[2];
value[5] = savedValue[5];
}
if (imageWidth > width || imageHeight > height) {
if (scaleWidth < width && scaleHeight < height) {
int target = WIDTH;
if (imageWidth < imageHeight)
target = HEIGHT;
if (target == WIDTH)
value[0] = value[4] = (float) width / imageWidth;
if (target == HEIGHT)
value[0] = value[4] = (float) height / imageHeight;
scaleWidth = (int) (imageWidth * value[0]);
scaleHeight = (int) (imageHeight * value[4]);
if (scaleWidth == width)
value[0] = value[4] = (float) width / imageWidth;
if (scaleHeight == height)
value[0] = value[4] = (float) height / imageHeight;
}
} else {
if (value[0] < 1)
value[0] = 1;
if (value[4] < 1)
value[4] = 1;
}
scaleWidth = (int) (imageWidth * value[0]);
scaleHeight = (int) (imageHeight * value[4]);
if (scaleWidth < width) {
value[2] = (float) width / 2 - (float) scaleWidth / 2;
}
if (scaleHeight < height) {
value[5] = (float) height / 2 - (float) scaleHeight / 2;
}
matrix.setValues(value);
savedMatrix2.set(matrix);
}
public void PaintSet() {
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
// getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(24, BlurMaskFilter.Blur.NORMAL);
}
public void colorChanged(int color) {
mPaint.setColor(color);
}
}
class PaintView extends ImageView {
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
// onDraw
private Paint mPaint;
// onTouch
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
public PaintView(Context context) {
this(context, null);
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mBitmap = Bitmap.createBitmap(1024, 1024, Bitmap.Config.ARGB_8888);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
// canvas.drawColor(0xFFAAAAAA);
super.onDraw(canvas);
mCanvas = canvas;
// canvas = mCanvas;
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
// canvas.drawBitmap(mBitmap, PaintScreen.matrix, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
public void clear() {
mPaint.reset();
// invalidate();
}
public void setMPaint(Paint paint) {
mPaint = paint;
}
private void touchStart(float x, float y) {
// mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(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;
}
}
private void touchUp() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
Log.d("PaintView", "ev ->" + event.getAction());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touchUp();
invalidate();
break;
}
return true;
}
public void cMatrix(Matrix matrix) {
mCanvas.setMatrix(matrix);
}
}