How to set a border to an imageview - android

I am working in an android application and I want to place an ImageView in a particular position in my view. For that I applied the particular code and worked successfully :
ImageView image = (ImageView) findViewById(R.id.imageView1);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.mrng);
Matrix mat = new Matrix();
mat.postRotate(350);
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(),bMap.getHeight(), mat, true);
image.setImageBitmap(bMapRotate);
Now I want to set a border to this image. For that I made a an shape xml and I have set as the background of the image view.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<stroke android:width="3dp" android:color="#000000" />
</shape>
But when I gave the background of the image view the shape it does not give the correct output.please help me.
I do not want a border around the ImageView, but rather border around the rotated image.

EDIT: I'm completely rewriting my answer based on the clarification of the question. Here's how I achieved what you want. The idea is to draw the frame and then rotate:
ImageView image = (ImageView) findViewById(R.id.TestImage);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
final int BORDER_WIDTH = 3;
final int BORDER_COLOR = Color.BLACK;
Bitmap res = Bitmap.createBitmap(bMap.getWidth() + 2 * BORDER_WIDTH,
bMap.getHeight() + 2 * BORDER_WIDTH,
bMap.getConfig());
Canvas c = new Canvas(res);
Paint p = new Paint();
p.setColor(BORDER_COLOR);
c.drawRect(0, 0, res.getWidth(), res.getHeight(), p);
p = new Paint(Paint.FILTER_BITMAP_FLAG);
c.drawBitmap(bMap, BORDER_WIDTH, BORDER_WIDTH, p);
Matrix mat = new Matrix();
mat.postRotate(350);
Bitmap bMapRotate = Bitmap.createBitmap(res, 0, 0, res.getWidth(), res.getHeight(), mat, true);
image.setImageBitmap(bMapRotate);
And here's the screenshot of the result:

There is way to put border around ImageView even any view in android. In XML put Four simple <View>'s on each side of the imageview. And these view's can be assigned any type of style. You can use relative layout in which you can place four borders easily around image view.
Kinda lengthy process but works.

Related

How to draw a circle in Drawable.draw

Q1. The R.drawable.wallpaper can show but the point cannot show.
Q2. Moreover, how to put an other image in
Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
I mean 2 pictures mix.
img = (ImageView) findViewById(R.id.img);
Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
bitmap.setBounds(0, 0, bitmap.getIntrinsicWidth(), bitmap.getIntrinsicHeight());
Bitmap point = Bitmap.createBitmap(
bitmap.getIntrinsicWidth(),
bitmap.getIntrinsicHeight(),
Bitmap.Config.ARGB_8888
);
Paint radius = new Paint(); radius.setColor(Color.RED);
radius.setStyle(Paint.Style.FILL); radius.setStrokeWidth(1);
radius.setAntiAlias(true);
Canvas canvas = new Canvas(point);
canvas.drawCircle((float)(5), (float)(5), 5, radius);
bitmap.draw(canvas);
img.setImageDrawable(bitmap);
Look in the Android SDK samples. There are several examples in the ApiDemos project:
/ApiDemos/res/drawable/
black_box.xml
shape_5.xml
etc
It will look something like this for a circle with a gradient fill:

(Android)How can I show a part of image?

I have an image like this->
And I want to show like this->
Then I can choose how much I can see(0~1,0=can not see,1=Whole picture,0.5=half picture,....etc,read from user input)
How to do that?
I tried to use android:scaleType but it is not working.
My best suggestion is to wrap your BitmapDrawable with a ClipDrawable.
ClipDrawable lets you define clipping for any other drawable, so instead of drawing the entire drawable, only a part of it will be drawn.
How would that work? Your ImageView can display a drawable - assignable through setImageDrawable(). Naturally, you would place a BitmapDrawable of your image bitmap there. If you wrap your BitmapDrawable first with ClipDrawable, and only then assign to the ImageView, you should be fine.
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/clip_source" />
and this is clip_source drawable:
<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:clipOrientation="vertical"
android:drawable="#drawable/your_own_drawable"
android:gravity="top" />
You can define the amount of clipping by calling the function setLevel() on your ClipDrawable (clip_source). A level of 0 means the image is completely hidden and a level of 10000 means the image is completely revealed. You can use any int value in the middle.
You'll have to set the level in code, so your code should first get a reference to the ClipDrawable. You can do this by running getDrawable() on your ImageView instance. When you have a reference to your ClipDrawable, simply run setLevel(5000) on it (or any other number 0-10000).
ImageView img = (ImageView) findViewById(R.id.imageView1);
mImageDrawable = (ClipDrawable) img.getDrawable();
mImageDrawable.setLevel(5000);
here is another way to achieve this
public static Bitmap getScaleBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()/2);
final RectF rectF = new RectF(rect);
final float roundPx = 0;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
Here in below line
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()/2);
set hight as you require..
Enjoy :)
I've achieved this by setting the scrollY on my ImageView in the markup. From android's documentation, clearly this is not an option if you're dealing with devices running less than API 14. Also, in my case, I'm using fixed size images that I'm loading based on application state, so they're always the same size. As such, I'm able to just implement it in markup. I realize this approach won't work for everyone.
I wrap the image in a layout that's half as tall as the icon and intentionally have the icon's size at it's actual size. Without the scrollY set, it displays only the top half of the image. Setting the scrollY moves it to where I want it - displaying only the lower half of the image.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/default_icon"
android:scrollY="50dp" />
</LinearLayout>
So, from my example, it's only displaying the bottom half of the icon.
Here's an easy way.. Create a separate layout in your main layout just for your images. Make sure it is realitive. Now put your image view for your pictures in side the layout and make it fill parent. OK now make a blank image and add that image view to the bottom of the layout and the top to the center of the layout. Just mess with the margins and size of the imageviews till it looks the way you want it. Hope this helps.
Convert your drawable into a bitmap and crop to get top of the image to form another bitmap, then display it into your image view.
// to convert drawable to bitmap
Bitmap resource = BitmapFactory.decodeResource(context.getResources(),
R.drawable.your_resource);
// to set width of bitmap to imageview's width if necessary,
int width = imageView.getMeasuredWidth();
// to crop the bitmap to specific width and height,
resource = Bitmap.createBitmap(resource, 0, 0, width, height);
here is the code to crop image into two part
public static Bitmap getScaleBitmap(Bitmap bitmap, int check) {
final Bitmap toBeCropped = bitmap;
final BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inTargetDensity = 1;
toBeCropped.setDensity(Bitmap.DENSITY_NONE);
int top = 0;
int bottom = 0;
int targetheight = 0;
if (check == 0) {// return 1st half of image
top = 0;
bottom = bitmap.getHeight() / 2;
} else {// return 2nd half of image
top = (bitmap.getHeight() / 2) - 10;
bottom = (bitmap.getHeight() / 2) - 10;
}
int fromHere = (int) (toBeCropped.getHeight() * 0.5);
Bitmap croppedBitmap = Bitmap.createBitmap(toBeCropped, 0, top, toBeCropped.getWidth(), bottom);
return croppedBitmap;
}

Creating bitmap from a drawable

I am going to be working on an app which requires drag/drop on a Canvas. Basically, I want to take a ShapeDrawable and convert it into a Bitmap which I can have the user drag around the screen. This is a simple exercise in itself.
However, I want to add text inside my shape. Is there a way I can add text to the drawable itself then convert to a bitmap? I looked into creating a TextView with a drawable as a background.
Is this the best way to do it? I sort of want to avoid creating TextViews in my code. Any advice is appreciated.
Edit 2/21/2013:
In response to JustDanyul's post I have the following code:
int width = 40;
int height = 40;
Bitmap.Config config = Bitmap.Config.ARGB_8888;
bitmap = Bitmap.createBitmap(width, height, config);
Canvas canvas = new Canvas(bitmap);
Resources res = context.getResources();
Drawable shape = res.getDrawable(R.drawable.miss_scarlet);
shape.draw(canvas);
Paint paint = new Paint();
paint.setTextSize(fontSize);
paint.setColor(Color.BLACK);
canvas.drawText(gameToken.getDbName(), 5, 5, paint);
My drawable is not showing up when I draw the bitmap on another canvas. The drawable itself is fine (I tested it as a background to a TextView). The text shows up. Am i missing something in this code?
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="4dp" />
<solid
android:color="#FF0000" />
<stroke
android:width="3dp"
android:color="#000000" />
</shape>
Edit #2 2/21/2013:
I added:
shape.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
to my code and now the drawable appears but my text is gone (or just hidden).
I would suggest you to try something like this, first, create an empty bitmap:
int w = 500
int h = 500; // or whatever sizes you need
Bitmap.Config config = Bitmap.Config.ARGB_8888;
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
Next step, create a new canvas instance, which renders onto your newly created bitmap
Canvas canvas = new Canvas(bitmap);
Now, you can draw the ShapeDrawable onto your empty bitmap using the ShapeDrawable's draw method
myshapedrawable.draw(canvas);
Finally, you can use the drawText method of the canvas instance to draw your text on the canvas.

create a image with color in android

Setting background doesn't seem to give any hint on size for android.
Hence I'm looking for a way to create an image with a specific color.
(would be better if could be done in xml)
in iOS this could be achieved by
+ (UIImage*)placeHolderImage
{
static UIImage* image = nil;
if(image != nil)
return image;
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// Seashell color
UIColor* color = [UIColor colorWithRed:255/255.0 green:245/255.0 blue:238/255.0 alpha:1.0];
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Here is the equivalent Android code:
// CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
Rect rect = new Rect(0, 0, 1, 1);
//UIGraphicsBeginImageContext(rect.size);
//CGContextRef context = UIGraphicsGetCurrentContext();
Bitmap image = Bitmap.createBitmap(rect.width(), rect.height(), Config.ARGB_8888);
Canvas canvas = new Canvas(image);
//UIColor* color = [UIColor colorWithRed:255/255.0 green:245/255.0 blue:238/255.0 alpha:1.0];
int color = Color.argb(255, 255, 245, 238);
//CGContextSetFillColorWithColor(context, [color CGColor]);
Paint paint = new Paint();
paint.setColor(color);
//CGContextFillRect(context, rect);
canvas.drawRect(rect, paint);
//image = UIGraphicsGetImageFromCurrentImageContext();
//UIGraphicsEndImageContext();
/** nothing to do here, we already have our image **/
/** and the canvas will be released by the GC **/
Now, if you want to do this in XML its much easier:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<size android:width="1px" android:height="1dp"/>
<solid android:color="#FFFFF5EE/>
</shape>
Although that won't give you a Bitmap, but a Drawable. It's just fine if you intend to just draw it somewhere. If you actually need a Bitmap, then you will have to use the above code to create a Canvas from a Bitmap and draw your Drawable into it.
This helps you in creating a bitmap image with a specific color.
firstly create a bitmap with name sampleBitmap like below
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap sampleBitmap = Bitmap.createBitmap(300, 300, conf); // this creates a MUTABLE bitmap
next use the following code to get each pixel of the created bitmap
// int[] pixels = new int[sampleBitmap.getHeight()*sampleBitmap.getWidth()];
for (int i=0; i < sampleBitmap.getWidth(); i++)
{
for (int j=0; j < sampleBitmap.getHeight(); i++)
{
sampleBitmap.setPixel(i, j, Color.rgb(someColor1, someColor2, someColor3));
}
}
using this you can set the bitmap to the listview item so that the listitem doesnt collapse

Android - Is it possible to declare an alpha mask directly within layer-list XML definition?

A newbie question
I have this layers.xml that I use as a source for an ImageView.
And two images, mask.png and image.jpg
layers.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<bitmap android:src="#drawable/image" android:gravity="center"/>
</item>
<item>
<bitmap android:src="#drawable/mask" android:gravity="center"/>
</item>
</layer-list>
ImageView:
<ImageView
android:id="#+id/img_B"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/layers"/>
At the moment the output is just the png over the image.
I would like the png to act as a mask, clipping the image using the png alpha channel like so:
Is that possible directly within the xml, or do I have to do it by code?
Thanks for your advice ;)
update:
at the moment I achieved my goal using code to replace the entire ImageView
ImageView img = (ImageView) findViewById(imgID);
Canvas canvas = new Canvas();
Bitmap mainImage = BitmapFactory.decodeResource(getResources(), R.drawable.img);
Bitmap mask = BitmapFactory.decodeResource(getResources(), R.drawable.mask);
Bitmap result = Bitmap.createBitmap(mainImage.getWidth(), mainImage.getHeight(), Bitmap.Config.ARGB_8888);
canvas.setBitmap(result);
Paint paint = new Paint();
paint.setFilterBitmap(false);
canvas.drawBitmap(mainImage, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
img.setImageBitmap(result);
img.invalidate();
Put your mask image in the folder drawable-nodpi.
Otherwise, the scaling will be wrong.
Here's some example code from an app. After the camera it adds a mask.
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE_CAPTURE) // && resultCode == RESULT_OK )
{
try
{
Bitmap cameraBmp = MediaStore.Images.Media.getBitmap(
State.mainActivity.getContentResolver(),
Uri.fromFile(Utils.tempFileForAnImage())
);
cameraBmp = ThumbnailUtils.extractThumbnail(cameraBmp, 256, 256);
Matrix m = new Matrix();
m.postRotate(Utils.neededRotation(Utils.tempFileForAnImage()));
// NOTE incredibly useful trick for cropping/resizing square
// http://stackoverflow.com/a/17733530/294884
cameraBmp = Bitmap.createBitmap(cameraBmp,
0, 0, cameraBmp.getWidth(), cameraBmp.getHeight(),
m, true);
// so, cameraBmp is now a Bitmap. Let's add the mask!!
// see Shiomi Schwartz's original!! http://stackoverflow.com/questions/8630365
Bitmap mask = BitmapFactory.decodeResource(
getResources(),
R.drawable.mask_android_256);
// NOTE THE MASK ** MUST ** BE IN YOUR nodpi folder
Bitmap result = Bitmap.createBitmap( 256,256, Bitmap.Config.ARGB_8888);
Canvas cc = new Canvas();
cc.setBitmap(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
cc.drawBitmap(cameraBmp, 0, 0, null);
cc.drawBitmap(mask, 0,0, paint);
// so, cameraBmp is now a Bitmap but it has been masked
yourImageViewForTheUser.setImageBitmap(result);
// make a "baos" ... we want PNG in this case ..
ByteArrayOutputStream baos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0, baos);
imageBytesRESULT = baos.toByteArray();
// typically you want the result as image bytes, example to send to Parse
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return;
}
}
.png files can have a alpha channel included when you create them and Android can use that to isolate the image as you explain.
Create an extra channel in GIMP or Photoshop or whatever image editor you use. This will be a monochrome channel (256 shades of white to black). Make a selection of the section you want to mask OUT click on the alpha channel and fill the selection area with black. Invert the selection, still in the alpha channel, and fill it with white. Save and export .png file as 24 bit with alpha (effectively 32 bit). Your file should render correctly.

Categories

Resources