Image Quality problems using Canvas and canvas.scale(Scale, Scale); - android

I am having Image Quality problems using Canvas and canvas.scale(Scale, Scale); they look exactly like the following:
android: quality of the images resized in runtime
I believe I have read all the posts on image quality problems when re-sizing bitmaps, but it doesn't seem to help when scaling with a Canvas scale(float scale).
I have tried many different options as suggested by the image quality posts.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inDither = false;
options.inSampleSize = 1;
options.inScaled = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;//I thought this would do it
CurrentPicture = BitmapFactory.decodeFile(path, options);//Also tried decodeStream()
PicturePaint = new Paint();
//PicturePaint = new Paint(Paint.FILTER_BITMAP_FLAG); //I also tried this
//PicturePaint = new Paint(Paint.ANTI_ALIAS_FLAG); //I also tried this
canvas.scale(Scale, Scale);
canvas.drawBitmap(CurrentPicture, 0, 0, PicturePaint);
I believe this the last barrier to achieving my goals. I am quite concerned as I am in trouble if I can't get the image quality problem solved. Any help is appreciated.
Thanks!
The system will not let me post a picture, so following is a link.
PictureSample

I don't no whether my answer is correct or not i have a code for canvas. i wish this might help you.
public class FotosurpriseActivity extends Activity {
/** Called when the activity is first created. */
Bitmap overlay;
Paint pTouch;
int X = -100;
int Y = -100;
Canvas c2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android);
Bitmap mBitmapover = BitmapFactory.decodeResource(getResources(), R.drawable.ss);
overlay = BitmapFactory.decodeResource(getResources(), R.drawable.ss).copy(Config.ARGB_8888, true);
c2 = new Canvas(overlay);
pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
// pTouch.setXfermode(new PorterDuffXfermode(Mode.TARGET);
pTouch.setColor(Color.TRANSPARENT);
pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
setContentView(new BitMapView(this, mBitmap, mBitmapover));
}
class BitMapView extends View {
Bitmap mBitmap = null;
Bitmap mBitmapover = null;
public BitMapView(Context context, Bitmap bm, Bitmap bmover) {
super(context);
mBitmap = bm;
mBitmapover = bmover;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();
break;
}
case MotionEvent.ACTION_MOVE: {
X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();
break;
}
case MotionEvent.ACTION_UP:
break;
}
return true;
}
#Override
protected void onDraw(Canvas canvas) {
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
/*
* double aspectRatio = ((double) mBitmap.getWidth()) /
* mBitmap.getHeight(); Rect dest = new Rect(0, 0,
* this.getWidth(),(int) (this.getHeight() / aspectRatio)); double
* aspectRatio2 = ((double) mBitmapover.getWidth()) /
* mBitmapover.getHeight(); Rect dest2 = new Rect(0, 0,
* this.getWidth(),(int) (this.getHeight() / aspectRatio2));
* canvas.drawBitmap(mBitmap, null, dest, paint);
* canvas.drawBitmap(mBitmapover, null, dest2, paint);
*/
// draw background
canvas.drawBitmap(mBitmap, 0, 0, null);
// copy the default overlay into temporary overlay and punch a hole
// in it
c2.drawBitmap(mBitmapover, 0, 0, null); // exclude this line to show
// all as you draw
c2.drawCircle(X, Y, 80, pTouch);
// draw the overlay over the background
canvas.drawBitmap(overlay, 0, 0, null);
}
}
}

Do you have a screenshot that would show the quality issue you are talking about? If filtering is enabled on the Paint it should be fine.

I tried many and many code.
I just add this in my manifest and I had the best quality image.
<uses-sdk android:minSdkVersion="9" />
I think the problem is the canvas is created in low resolution. If u try to print on the screen the resolution of your device, u can see it is wrong.
With the add in the manifest the resolution change.

Related

Drawing Oval on canvas with PAINT object in Android

In the following code, I'm trying to draw an oval which be enlarged with time.
Bitmap currBitmap = null;
Canvas currCanvas = null;
//Config Paint Case2
final Paint currPaint = new Paint();
List BlocksList = null;
boolean bSet = false;
public void DrawOval(Bitmap src, int nRadiusprct)
{
// image size
int width = src.getWidth();
int height = src.getHeight();
//create bitmap output
if(currBitmap == null)
currBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// set canvas for painting
if(currCanvas == null)
{
currCanvas = new Canvas(currBitmap);
currCanvas.drawARGB(0, 0, 0, 0);
MainActivity.imgMain.setImageBitmap(currBitmap);
}
// config paint Case1
/*final Paint currPaint = new Paint();
currPaint.setAntiAlias(true);
currPaint.setColor(Color.BLACK);*/
// config paint Case2
if(!bSet)
{
currPaint.setAntiAlias(true);
currPaint.setColor(Color.BLACK);
// create Xfer mode
currPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
bSet = true;
}
// config rectangle for embedding
int nMidWidth = width/2;
int nMidHeight = height/2;
float fPercent = (nRadiusprct / 100.0f);
float fLeft = nMidWidth * (1 - fPercent);
float fRight = nMidWidth * (1 + fPercent);
float fTop = nMidHeight * (1 - fPercent);
float fBottom = nMidHeight * (1 + fPercent);
final Rect rect = new Rect(0, 0, width, height);
final RectF rectF = new RectF(fLeft, fTop, fRight, fBottom);
currCanvas.drawOval(rectF, currPaint);
// create Xfer mode, Config Paint Case1
//currPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
currCanvas.drawBitmap(src, rect, rect, currPaint);
MainActivity.imgMain.invalidate();
}
Now, As you can see write a comment "Config Paint Case1" or "Config Paint Case2", case1 represents the case where I create a paint instance each time the method is called, while case 2 represents where I define a member object in the class so I can use it whenever I need, the problem that when I'm using the first case everything is working perfectly and accurate, while when I'm using the second case nothing happened, The main thing that in my opinion I don't need to create a paint object each time so I need to optimize my code more and more, but why this happened here.....
Finally I got an answer to this question, A great help by this article Transparency with JPEGs done right that describes how PorterDuff modes are work, In that article I found this Xfermodes Example which gives me where is the error and here is the description.
Actually, I don't need to create a paint object everytime, what I need is to deal with the xfermodes in a correct way, the perfect code is:
Bitmap currBitmap = null;
Canvas currCanvas = null;
//Config Paint Case2
final Paint currPaint = new Paint();
List BlocksList = null;
boolean bSet = false;
public void DrawOval(Bitmap src, int nRadiusprct)
{
// image size
int width = src.getWidth();
int height = src.getHeight();
//create bitmap output
if(currBitmap == null)
currBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// set canvas for painting
if(currCanvas == null)
{
currCanvas = new Canvas(currBitmap);
MainActivity.imgMain.setImageBitmap(currBitmap);
}
// config paint Case2
if(!bSet)
{
currPaint.setAntiAlias(true);
currPaint.setColor(Color.BLACK);
bSet = true;
}
// config rectangle for embedding
int nMidWidth = width/2;
int nMidHeight = height/2;
float fPercent = (nRadiusprct / 100.0f);
float fLeft = nMidWidth * (1 - fPercent);
float fRight = nMidWidth * (1 + fPercent);
float fTop = nMidHeight * (1 - fPercent);
float fBottom = nMidHeight * (1 + fPercent);
final Rect rect = new Rect(0, 0, width, height);
final RectF rectF = new RectF(fLeft, fTop, fRight, fBottom);
Xfermode BeforEPaintXferMode = currPaint.getXfermode();
currCanvas.drawOval(rectF, currPaint);
// create Xfer mode
currPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// draw source image to canvas
currCanvas.drawBitmap(src, rect, rect, currPaint);
currPaint.setXfermode(BeforEPaintXferMode);
MainActivity.imgMain.invalidate();
}
Now, as you can see I just storing the current xfermode before painting, then I set it to SRC_IN mode and finally, I go back to the original one. and everything is working perfectly.

bitmapshader and canvas.scaling android

Does anyone have a hint or explanation for the following problem ?
I draw a path with a bitmapshader. When canvas is not scaled, it looks good ( first picture ).
When I scale into ( zooming in ) the bitmapshader is not be scaled and looks very ugly. I tried several things with recreating the bitmapshader after zooming in, but did not succeed :-(. Does anyone have a hint ?
No Scaling it looks good :
when scaling it looks ugly:
Code :
canvas.scale(scalex, scaley);
canvas.translate(itranslatex, itranslatey);
fillBMP = makePatternCross(fscalex, 1, Color.GREEN/*,fscalex,fscaley*/);
fillBMPshader = new BitmapShader(fillBMP, BitmapShader.TileMode.REPEAT, BitmapShader.TileMode.REPEAT);
paintshader = new Paint();
paintshader.setShader(fillBMPshader);
canvas.drawPath(cpath.path, paintshader);
private static Bitmap makePatternCross(float fSize, float fStrokewith,int iColor) {
Log.v("Create Patter makePatternCross","makePatternCross");
float fBitmapSizeOrig = 10;
fBitmapSizeOrig=fBitmapSizeOrig*fSize;
Bitmap bm = Bitmap.createBitmap((int)fBitmapSizeOrig,(int) fBitmapSizeOrig,Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
//c.scale(200, 200);
c.drawColor(Color.WHITE);
Paint p = new Paint();
p.setColor(iColor);
//p.setStrokeWidth(iStrokewith);
p.setStrokeWidth(fStrokewith/fSize);
p.setStrokeWidth((float) 0.000001);
c.drawLine(0, 0, fBitmapSizeOrig, fBitmapSizeOrig, p);
c.drawLine(0, fBitmapSizeOrig, fBitmapSizeOrig, 0, p);
if (fSize != 1) {
int iNewSize = (int) (( fBitmapSizeOrig) * fSize);
bm = Bitmap.createScaledBitmap(bm, iNewSize, iNewSize, false);
}
int width = bm.getWidth();
int height = bm.getHeight();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (bm.getPixel(x, y) == Color.WHITE) {
bm.setPixel(x, y, Color.TRANSPARENT);
} else {
// bm.setPixel(x, y, bm.getPixel(x, y));
}
}
}
return bm;
}
Not sure exactly if this is what your looking for. But if you use a matrix to scale the bitmap it retains more quality than normal scaling.
Matrix matrix = new Matrix();
matrix.postScale(desiredScale, desiredScale);
Bitmap scaledBitmap = Bitmap.createBitmap(sampledSrcBitmap, 0, 0, sampledSrcBitmap.getWidth(), sampledSrcBitmap.getHeight(), matrix, true);
Also when going from a lesser resolution to a higher you can try this as well:
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(a.getResources(), path, options);

How might I add a watermark effect to an image in Android?

I have an image with frames and I need to add a watermark effect. How might I do this?
I found great tutorial on Android Image Processing here.
public static Bitmap mark(Bitmap src, String watermark, Point location, Color color, int alpha, int size, boolean underline) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(color);
paint.setAlpha(alpha);
paint.setTextSize(size);
paint.setAntiAlias(true);
paint.setUnderlineText(underline);
canvas.drawText(watermark, location.x, location.y, paint);
return result;
}
Thanks to Pete Houston who shares such useful tutorial on basic image processing.
For others reference, if you want to add the logo of your application (which is in your drawable folder(s)) on top of image use following method:
private Bitmap addWaterMark(Bitmap src) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Bitmap waterMark = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.logo);
canvas.drawBitmap(waterMark, 0, 0, null);
return result;
}
If someone is still searching for this, I found a good solution here
It adds a watermark to the bottom right portion and scales it according to the source image which was exactly what I was looking for.
/**
* Embeds an image watermark over a source image to produce
* a watermarked one.
* #param source The source image where watermark should be placed
* #param watermark Watermark image to place
* #param ratio A float value < 1 to give the ratio of watermark's height to image's height,
* try changing this from 0.20 to 0.60 to obtain right results
*/
public static Bitmap addWatermark(Bitmap source, Bitmap watermark, float ratio) {
Canvas canvas;
Paint paint;
Bitmap bmp;
Matrix matrix;
RectF r;
int width, height;
float scale;
width = source.getWidth();
height = source.getHeight();
// Create the new bitmap
bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);
// Copy the original bitmap into the new one
canvas = new Canvas(bmp);
canvas.drawBitmap(source, 0, 0, paint);
// Scale the watermark to be approximately to the ratio given of the source image height
scale = (float) (((float) height * ratio) / (float) watermark.getHeight());
// Create the matrix
matrix = new Matrix();
matrix.postScale(scale, scale);
// Determine the post-scaled size of the watermark
r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight());
matrix.mapRect(r);
// Move the watermark to the bottom right corner
matrix.postTranslate(width - r.width(), height - r.height());
// Draw the watermark
canvas.drawBitmap(watermark, matrix, paint);
return bmp;
}
And it is well commented which is what is a huge plus!
It seems you are looking for a waterrippleeffect as this one. Checkout the complete source code. Also check the screenshot how does the effect look like.
In Kotlin:
Note: Its just modified code of above answers
private fun mark(src: Bitmap, watermark: String): Bitmap {
val w = src.width
val h = src.height
val result = Bitmap.createBitmap(w, h, src.config)
val canvas = Canvas(result)
canvas.drawBitmap(src, 0f, 0f, null)
val paint = Paint()
paint.color = Color.RED
paint.textSize = 10f
paint.isAntiAlias = true
paint.isUnderlineText = true
canvas.drawText(watermark, 20f, 25f, paint)
return result
}
val imageBitmap = mark(yourBitmap, "Your Text")
binding.meetProofImageView.setImageBitmap(imageBitmap)
You can use androidWM to add a watermark into your image, even with invisible watermarks:
add dependence:
dependencies {
...
implementation 'com.huangyz0918:androidwm:0.2.3'
...
}
and java code:
WatermarkText watermarkText = new WatermarkText(“Hello World”)
.setPositionX(0.5)
.setPositionY(0.5)
.setTextAlpha(100)
.setTextColor(Color.WHITE)
.setTextFont(R.font.champagne)
.setTextShadow(0.1f, 5, 5, Color.BLUE);
WatermarkBuilder.create(this, backgroundBitmap)
.loadWatermarkText(watermarkText)
.getWatermark()
.setToImageView(backgroundView);
You can easily add an image type watermark or a text watermark like this, and the library size is smaller than 30Kb.
I tried a few libraries mentioned in other posts, like this, but unfortunately it is missing, and not downloadable now. So I followed AndroidLearner 's answer above, but after tweaking the code a little bit, for those of you who are having trouble rotating the watermark, and what values are valid for the various methods of Paint class, so that the text shows rotated at an angle(like most of the company watermarks do), you can use the below code.
Note that, w and h are the screen width and height respectively, which you can calculate easily, there are tons of ways you can find on stackoverflow only.
public static Bitmap waterMarkBitmap(Bitmap src, String watermark) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap mutableBitmap = Utils.getMutableBitmap(src);
Bitmap result = Bitmap.createBitmap(w, h, mutableBitmap.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0f, 0f, null);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(92f);
paint.setAntiAlias(true);
paint.setAlpha(70); // accepts value between 0 to 255, 0 means 100% transparent, 255 means 100% opaque.
paint.setUnderlineText(false);
canvas.rotate(45, w / 10f, h / 4f);
canvas.drawText(watermark, w / 10f, h / 4f, paint);
canvas.rotate(-45, w / 10f, h / 4f);
return result;
}
It rotates the text watermark by 45 degrees, and places it at the centre of the bitmap.
Also note that, in case you are not able to get watermark, it might be the case that the bitmap you are using as source is immutable. For this worst case scenario, you can use below method to create a mutable bitmap from an immutable one.
public static Bitmap getMutableBitmap(Bitmap immutableBitmap) {
if (immutableBitmap.isMutable()) {
return immutableBitmap;
}
Bitmap workingBitmap = Bitmap.createBitmap(immutableBitmap);
return workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
}
I found above method inside here. I have tested using both the methods in my application, and it works perfectly after I added above tweaks. Try it and let me know if it works or not.
use framelayout. put two imageviews inside the framelayout and specify the position of the watermark imageview.

Scale & rotate Bitmap using Matrix in Android

I'm trying to scale and rotate in single operation before creting the final bitmap but the preRotate, postConcat doesn't seem to work.
Bitmap bmp = ... original image ...
Matrix m = new Matrix()
m.setScale(x, y);
m.preRotate(degrees, (float) width / 2, (float) height / 2);
Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
It only applies the scale and not rotation.
The answer was given, but to make things more clear to anyone reading this:
1) if you wish to perform ONE transformation in your bitmap, you CAN use SET (setRotate, setScale etc).
But note that any call to a "set" method OVERRIDES other transformations. It's like a new matrix. That's why OP's rotation was not working. These calls are not performed line by line. It's like they are scheduled to be done at runtime by the GPU when the new bitmap is being drawn. It's like when resolving your matrix, GPU rotated it, but then, created a scaled new one, ignoring previous matrix.
2) if you wish to perform more then one transformation, then you MUST use "pre" or "post" methods.
And what is the difference between a postRotate and a preRotate, for example? Well, this matrix math stuff is not my strength, but what I know is that the graphic cards make these transformations using matrix multiplication. It seems to be way more efficient. And as far as I remember from school, when multiplicating matrices the order IS important. A X B != B X A. So, scale a matrix and then rotate it is different from rotate and then scale it.
BUUUUT, as far as the final result in the screen is the same, we high level programmers usually do not need to know these differences. The GPU does.
Well, in that rare cases when you are performing really complicated matrix operations, and results are not what you expected or the performance is terrible and you need to deeply understand these methods to fix your code, well, then android documentation can not be of much help anyway. Instead, a good Linear Algebra book would be your best friend. ;)
This is the code
public class Bitmaptest extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(45);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
newWidth, newHeight, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
// add ImageView to the Layout
linLayout.addView(imageView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
)
);
// set LinearLayout as ContentView
setContentView(linLayout);
}
}
If you face the issue of OutOfMemory with above answers, than use below:
Bitmap MyFinalBitmap = Bitmap.createBitmap(CurrentBitmap, 0, 0,CurrentBitmap.getWidth()/2, CurrentBitmap.getHeight()/2,matrix, true);
Canvas holds a matrix stack und you can use it with the methods:
Canvas.save()
Doc:
/**
* Saves the current matrix and clip onto a private stack.
*
* Subsequent calls to translate,scale,rotate,skew,concat or clipRect,
* clipPath will all operate as usual, but when the balancing call to
* restore() is made, those calls will be forgotten, and the settings that
* existed before the save() will be reinstated.
*
* #return The value to pass to restoreToCount() to balance this save()
*/
Canvas.restore()
Doc:
/**
* This call balances a previous call to save(), and is used to remove all
* modifications to the matrix/clip state since the last save call. It is
* an error to call restore() more times than save() was called.
*/
example:
A custom View(Android) which looks like a rotary knob(e.g. potentiometer)
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
viewX = getWidth(); //views width
viewY = getHeight(); //views height
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); //a must call for every custom view
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
double tempAngel = 3.6 * barValue;
int deltaX = bitmap.getWidth() / 2;
int deltaY = bitmap.getHeight() / 2;
...
canvas.save();
canvas.translate(viewX / 2, viewY / 2); //translate drawing point to center
canvas.rotate((float) tempAngel); //rotate matrix
canvas.save(); //save matrix. your drawing point is still at (viewX / 2, viewY / 2)
canvas.translate(deltaX * -1, deltaY * -1); //translate drawing point a bit up and left to draw the bitmap in the middle
canvas.drawBitmap(bitmap, 0,0, bitmapPaint); // draw bitmap to the tranlated point at 0,0
canvas.restore(); //must calls...
canvas.restore();
}
All of the previous answer assume that this change to the bitmap is being made in a view. However in my case I was making the change to be saved out. Figured I would answer it for those in a similar boat.
There are two ways to do translation. Below dx is the translation in the X axis, and dy is the translation in the Y axis. The other variables should be self explanatory.
1 - Translation within the image (without rotation)
val newBitmap = Bitmap.createBitmap(originalBitmap, dx, dy, newWidth, newHeight, matrix, false)
2 - Complex matrix
matrix.postTranslate(dx, dy)
val newBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(newBitmap)
canvas.drawBitmap(originalBitmap, matrix, null)
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(rotation);
rotatedBitmap = Bitmap.createBitmap(loadedImage, 0, 0,loadedImage.getWidth(), loadedImage.getHeight(),rotateMatrix, false);
Refer to the following code, seems to work. In your code you are defining Matrix as m but referring to it as matrix
public class FourthActivity extends Activity {
private static final int WIDTH = 50;
private static final int HEIGHT = 50;
private static final int STRIDE = 64;
private static int[] createColors() {
int[] colors = new int[STRIDE * HEIGHT];
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int r = x * 255 / (WIDTH - 1);
int g = y * 255 / (HEIGHT - 1);
int b = 255 - Math.min(r, g);
int a = Math.max(r, g);
colors[y * STRIDE + x] = (a << 24) | (r << 16) | (g << 8) | b;
}
}
return colors;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
final ImageView view1 = (ImageView) findViewById(R.id.imageView1);
int[] colors = createColors();
final Bitmap bmp1 = Bitmap.createBitmap(colors, 0, STRIDE, WIDTH, HEIGHT,
Bitmap.Config.ARGB_8888);
view1.setImageBitmap(bmp1);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Matrix matrix = new Matrix();
matrix.setScale(2, 2);
matrix.preRotate(45, (float) WIDTH / 2, (float) HEIGHT / 2);
Bitmap bmp2 = Bitmap.createBitmap(bmp1, 0, 0,
bmp1.getWidth(), bmp1.getHeight(), matrix, true);
ImageView view2 = (ImageView) findViewById(R.id.imageView2);
view2.setImageBitmap(bmp2);
}
});
}
}
Use matrix to scale area of original bitmap to 50% and compress bitmap until it's size < 200k
Compress bitmap to a specific byte size in Android

Rotating Image on A canvas in android

I want to Rotate Image according to a specific angle in android ,some thing like a compass...
I have this code...it works on drawPath()
but i want to replace the path and the Drawing thing with image..
I tried to create a bitmap image ,DrawBitmapImage , but the image does not Rotate like the path..Any Help PLease?
public void draw(Canvas canvas) {
double angle = calculateAngle(currentLongitude, currentLatitude, targetLongitude, targetLatitude);
//Correction;
angle-=90;
//Correction for azimuth
angle-=azimuth;
if((getContext() instanceof Activity) && ((Activity)getContext()).getWindowManager().getDefaultDisplay().getOrientation()==Configuration.ORIENTATION_PORTRAIT)angle-=90;
while(angle<0)angle=angle+360;
Rect rect = canvas.getClipBounds();
int height = rect.bottom-rect.top;
int width = rect.right-rect.left;
int left = rect.left;
int top = rect.top;
if(height>width){
top+=(height-width)/2;
height=width;
}
if(width>height){
left+=(width-height)/2;
width=height;
}
float centerwidth = width/2f;
float centerheight = height/2f;
Paint p = new Paint();
p.setColor(color);
p.setStyle(Paint.Style.FILL);
p.setAntiAlias(true);
float startX = left+(float)(centerwidth+Math.cos(deg2rad(angle))*width/3.0);
float startY = top+(float)(centerheight+Math.sin(deg2rad(angle))*height/3.0);
Path path = new Path();
path.moveTo(
startX,
startY);
path.lineTo(
left+(float)(centerwidth+Math.cos(deg2rad(angle+140))*width/4.0),
top+(float)(centerheight+Math.sin(deg2rad(angle+140))*height/4.0));
path.lineTo(
left+(float)centerwidth,
top+(float)centerheight
);
path.lineTo(
left+(float)(centerwidth+Math.cos(deg2rad(angle+220))*width/4.0),
top+(float)(centerheight+Math.sin(deg2rad(angle+220))*height/4.0)
);
path.lineTo(
startX,
startY
);
canvas.drawPath(path, p);
}
You can either rotate your bitmap when you draw it by using a matrix:
Matrix matrix = new Matrix();
matrix.setRotate(angle, imageCenterX, imageCenterY);
yourCanvas.drawBitmap(yourBitmap, matrix, null);
You can also do it by rotating the canvas before drawing:
yourCanvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
yourCanvas.rotate(-angle);
yourCanvas.drawBitmap(yourBitmap, left, top, null);
yourCanvas.restore();
Pick the one that suits you the best.
You have to rotate the canvas first and then draw whatever you want. Then the object drawn will be appeared as rotated on screen.
canvas.rotate(45); // degrees to rotate
try this its good way.
Check this tutorial you will get information about how to draw bitmap and how to rotate canvas
Check complete tutorial
This is the only one that worked for me with no problem.
private Bitmap rotateBitmap(Bitmap bitmap, int rotationAngleDegree){
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int
newW=w, newH=h;
if (rotationAngleDegree==90 || rotationAngleDegree==270){
newW = h;
newH = w;
}
Bitmap rotatedBitmap = Bitmap.createBitmap(newW,newH, bitmap.getConfig());
Canvas canvas = new Canvas(rotatedBitmap);
Rect rect = new Rect(0,0,newW, newH);
Matrix matrix = new Matrix();
float px = rect.exactCenterX();
float py = rect.exactCenterY();
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postRotate(rotationAngleDegree);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, new Paint( Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG ));
matrix.reset();
return rotatedBitmap;
}
Based on #Sakthi 's code, but add scaling :)
Rect rect = new Rect(0,0,canvas.getWidth(), canvas.getHeight());
Matrix matrix = new Matrix();
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postScale(
((float)rect.width()) / bitmap.getWidth(),
((float)rect.height()) / bitmap.getHeight());
matrix.postRotate(180);
matrix.postTranslate(rect.exactCenterX(), rect.exactCenterY());
canvas.drawBitmap(bitmap, matrix, null);
#Reham: Look at this example code below,
public class bitmaptest extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(45);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
// add ImageView to the Layout
linLayout.addView(imageView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
)
);
// set LinearLayout as ContentView
setContentView(linLayout);
}
}
you have to use the matrix to rotate image look the lines
matrix.postRotate(45); -
this will rotate the image to 45 degrees
Hope this help you ...thx
Use following code. it worked for me
float rotation = 30.0f;
Bitmap bitmap = your bitmap
Rect rect = new Rect(100,100,bitmap.width, bitmap.height);
Matrix matrix = new Matrix();
float px = rect.exactCenterX();
float py = rect.exactCenterY();
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postRotate(rotation);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, null);
matrix.reset();
invalidate();

Categories

Resources