Is there a way to overlay a bitmap onto a shape in an XML drawable? I want to put an icon on top of an oval shape.
public static Bitmap overlayBitmapToCenter(Bitmap bitmap1, Bitmap bitmap2) {
int bitmap1Width = bitmap1.getWidth();
int bitmap1Height = bitmap1.getHeight();
int bitmap2Width = bitmap2.getWidth();
int bitmap2Height = bitmap2.getHeight();
float marginLeft = (float) (bitmap1Width * 0.5 - bitmap2Width * 0.5);
float marginTop = (float) (bitmap1Height * 0.5 - bitmap2Height * 0.5);
Bitmap overlayBitmap = Bitmap.createBitmap(bitmap1Width, bitmap1Height, bitmap1.getConfig());
Canvas canvas = new Canvas(overlayBitmap);
canvas.drawBitmap(bitmap1, new Matrix(), null);
canvas.drawBitmap(bitmap2, marginLeft, marginTop, null);
return overlayBitmap;
}
Related
I'm trying to add padding to a bitmap programmatically however, when I add the padding to the top, it's removed from the bottom. When I add it to the bottom, it's removed from the top.
Adding padding to the top
Bitmap backgroundBitmap = ((BitmapDrawable) backgroundDrawable).getBitmap();
int padding = 60;
int positionLeft = 0;
int positionTop = 0;
Bitmap mainBitmap = Bitmap.createBitmap(
backgroundBitmap.getWidth(), //Adding top padding here
backgroundBitmap.getHeight() + padding,
Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(mainBitmap);
canvas.drawBitmap(
backgroundBitmap,
positionLeft + padding,
positionTop + padding,
null
);
Adding padding to the bottom removes the top padding
Bitmap backgroundBitmap = ((BitmapDrawable) backgroundDrawable).getBitmap();
int padding = 60;
int positionLeft = 0;
int positionTop = 0;
Bitmap mainBitmap = Bitmap.createBitmap(
backgroundBitmap.getWidth(),
backgroundBitmap.getHeight() + padding,
Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(mainBitmap);
canvas.drawBitmap(
backgroundBitmap,
positionLeft + padding,
positionTop, //Adding bottom padding here
null
);
Can't figure out
how can I add padding to all 4 sides to my backgroundBitmap bitmap?
Edit1:____________________________________________
I've also tried this solution:
https://stackoverflow.com/a/15525394/11110509
which adds a border to the bitmap, however it's only adding the border to the top and left. Doesn't include the bottom and right
private Bitmap addWhiteBorder(Bitmap bmp, int borderSize) {
Bitmap bmpWithBorder = Bitmap.createBitmap(bmp.getWidth() + borderSize * 2, bmp.getHeight() + borderSize * 2, bmp.getConfig());
Canvas canvas = new Canvas(bmpWithBorder);
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(bmp, borderSize, borderSize, null);
return bmpWithBorder;
}
Bitmap backgroundBitmap = ((BitmapDrawable) backgroundDrawable).getBitmap();
int padding = 60;
int positionLeft = 0;
int positionTop = 0;
Bitmap mainBitmap = Bitmap.createBitmap(
backgroundBitmap.getWidth(),
backgroundBitmap.getHeight(),
Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(mainBitmap);
canvas.drawBitmap(
addWhiteBorder(backgroundBitmap, padding),
positionLeft,
positionTop,
null
);
This may or may not help you but don't pad the Bitmap, add it to a container in the view like a linearlayout and then pad the linearlayout . It should be a lot easier to deal with.
int left = (canvas.getWidth()-mainBitmap.getWidth())/2;
int top = (canvas.getHeight()-mainBitmap.getHeight())/2;
canvas.drawBitmap(mainBitmap, left, top, null);
This should get the the bitmap to the center in relation to the canvas.
I got it from here if you need more info How to align the canvas object to center of the screen?
The main issue was that I didn't have enough padding space in my main Bitmap
Bitmap backgroundBitmap = ((BitmapDrawable) backgroundDrawable).getBitmap();
Bitmap appLogoBitmap = ((BitmapDrawable) appLogoDrawable).getBitmap();
int padding = 60;
int positionLeft = 0;
int positionTop = 0;
Bitmap mainBitmap = Bitmap.createBitmap(
backgroundBitmap.getWidth() + (padding * 2), //Adding the * 2 helped display the padding
backgroundBitmap.getHeight() + (padding * 2),
Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(mainBitmap);
canvas.drawBitmap(
addWhiteBorder(backgroundBitmap, padding),
positionLeft,
positionTop,
null
);
And the function to add the padding:
private Bitmap addWhiteBorder(Bitmap bmp, int borderSize) {
Bitmap bmpWithBorder = Bitmap.createBitmap(bmp.getWidth() + borderSize * 2, bmp.getHeight() + borderSize * 2, bmp.getConfig());
Canvas canvas = new Canvas(bmpWithBorder);
canvas.drawColor(Color.parseColor("#63A4FF"));
canvas.drawBitmap(bmp, borderSize, borderSize, null);
return bmpWithBorder;
}
I wanted to draw a contour around the picture by drawing and expanding a second picture in the Background, but I wasn't very successful, how can I draw a regular stroke?
The contour I drew:
The contour I want to draw:
My Code;
private Bitmap ContourBitmap() {
int strokeWidth = 8;
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.flower_icon);
Bitmap newStrokedBitmap = Bitmap.createBitmap(originalBitmap.getWidth() + 2 * strokeWidth,
originalBitmap.getHeight() + 2 * strokeWidth, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newStrokedBitmap);
float scaleX = (originalBitmap.getWidth() + 2.0f * strokeWidth) / originalBitmap.getWidth();
float scaleY = (originalBitmap.getHeight() + 2.0f * strokeWidth) / originalBitmap.getHeight();
Matrix matrix = new Matrix();
matrix.setScale(scaleX, scaleY);
canvas.drawBitmap(originalBitmap, matrix, null);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_ATOP); //Color.WHITE is stroke color
canvas.drawBitmap(originalBitmap, strokeWidth, strokeWidth, null);
}
I think you are on the right track...
Here is a strategy, instead of scaling just draw the same original picture a few times each time slightly offset, see sample below:
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
var img = new Image;
img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";
var s = 10, // thickness scale
x = 15, // final position
y = 15;
function draw() {
ctx.globalAlpha = 0.2
ctx.filter = 'brightness(0%)'
for (i = 0; i < 360; i++)
ctx.drawImage(img, x + Math.sin(i) * s, y + Math.cos(i) * s);
ctx.globalAlpha = 1
ctx.filter = 'none'
ctx.drawImage(img, x, y);
}
<canvas id=canvas width=350 height=600></canvas>
I applied a filter = 'brightness(0%)' but there are many more you can apply:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter
I'm using HTML canvas but that same idea should "translate" nicely to an android canvas.
I have been struggling to get the preview of a PDF in the Android Print Framework to match the print output. However, I am able to get the output to match as a bitmap. However, if I scale the bitmap and put whitespace around the bitmap, the Print Framework crops out the whitespace. So, to prevent that from happening, I would like to draw a thin border around the edge of the entire Canvas.
This is the code that I have to scale the bitmap:
public static Bitmap captureScreen(View v) {
Bitmap screenshot = null;
Bitmap output = null;
try {
if (v != null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
int width = screenshot.getWidth();
int height = screenshot.getHeight();
int scaledWidth = (int) (width * 0.5);
int scaledHeight = (int) (height * 0.5);
output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Bitmap scaled = Bitmap.createScaledBitmap(screenshot, scaledWidth, scaledHeight, false);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
int distX = (width - scaledWidth) / 2;
int distY = (height - scaledHeight) / 2;
canvas.drawBitmap(scaled, distX, distY, paint);
v.draw(canvas);
}
} catch (Exception e) {
Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return output;
}
I would like to draw a thin black border around the entire canvas for I can prevent the whitespace from being cropped out by the Print Framework.
Well, you have the width and height of the canvas, just call Canvas.drawRect(0, 0, width - 1, height - 1, strokePaint)?
In this Image I want text to totally be in the triangle with CYAN color.
I have created my own ImageView:
public class BookImageView extends android.support.v7.widget.AppCompatImageView {
private static final Float DISCOUNT_SIDE_SIZE = 0.33333F;
private Bitmap bitmap;
private Paint drawPaint = new Paint();
private Paint trianglePaint = new Paint();
{
trianglePaint.setColor(Constants.DISCOUNT_COLOR);
trianglePaint.setStyle(Paint.Style.FILL);
trianglePaint.setShadowLayer(10.0f, 10.0f, 10.0f, Color.parseColor("#7f000000"));
trianglePaint.setAntiAlias(true);
drawPaint.setColor(Color.BLACK);
drawPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
drawPaint.setShadowLayer(1f, 0f, 1f, Color.BLACK);
}
// Constractors ...
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (bitmap != null) {
Bitmap tempBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(bitmap, 0, 0, null);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
float size = bitmap.getWidth() * DISCOUNT_SIDE_SIZE;
path.lineTo(size, 0);
path.lineTo(0, size);
path.lineTo(0, 0);
path.close();
tempCanvas.drawPath(path, trianglePaint);
float scale = getResources().getDisplayMetrics().density;
drawPaint.setTextSize((int) (14 * scale));
Rect textBounds = new Rect();
drawPaint.getTextBounds("50%", 0, "50%".length(), textBounds);
int x = (int) (size / 2) - textBounds.width() / 2;
int y = (int) (size / 2) - textBounds.height() / 2;
tempCanvas.save();
tempCanvas.rotate(-45, x, y);
tempCanvas.drawText("50%", x, y, drawPaint);
tempCanvas.restore();
setImageDrawable(new BitmapDrawable(getContext().getResources(), tempBitmap));
}
}
#Override
public void setImageBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
invalidate();
}
}
what can I do to solve this problem ?
You can try something like this
1) Measure the width of your text
Use measureText
2) From the point you are drawing calculate the width remaining to draw
3) Now depending on the use case you can curtail the length of text or scale the text as needed
int textWidthRequired = (int) drawPaint.measureText(textToDraw);
int widthRemainingToDraw = totalWidth/2 - textDrawX;
if(textWidthRequired > widthRemainingToDraw){
//handling
}
// draw text
tempCanvas.drawText(textToDraw,textDrawX, textDrawY, drawPaint);
Depending on how high up you want the text to be, you can use properties of similar triangles to first determine the maximum width of the text. In your case, size = the triangle's base, and size = the triangle's height/altitude. Let's define two variables:
Correction: The altitude won't be equal to the base. You'd need to calculate the altitude in order to use the below solution.
float triangleBase = size; // triangle base
float triangleAltitude = size; // Calculate this.
Let's say we want the text to be halfway up the center of the triangle:
float textYHeight = triangleHeight/2;
We figure out the width of the triangle at this point by using the following formula since the sides of similar triangles are proportional:
baseOfTriangleA/baseOfTriangleB = altitudeOfTriangleA/altitudeOfTriangleB;
float triangleWidthAtTextYLocation = (textYHeight * triangleBase)/triangleAltitude;
Now that we know what the width of the triangle is at this location, we can just iterate through different text scales until the text width is less than the value triangleWidthAtTextYlocation.
float scale = getResources().getDisplayMetrics().density;
int scaleFactor = 0;
drawPaint.setTextSize((int) (scaleFactor * scale));
Rect textBounds = new Rect();
drawPaint.getTextBounds("50%", 0, "50%".length(), textBounds);
while(textBounds.length < triangleWidthAtTextYLocation){
// Re-measure the text until it exceeds the width
scaleFactor++;
drawPaint.setTextSize((int) (scaleFactor * scale));
drawPaint.getTextBounds("50%", 0, "50%".length(), textBounds);
}
// Once we know the scaleFactor that puts it over the width of the triangle
// at that location, we reduce it by 1 to be just under that width:
scaleFactor = Maths.abs(scaleFactor - 1);
// final text size:
drawPaint.setTextSize((int) (scaleFactor * scale));
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();