Android imageview example

Android imageview example DEFAULT

ImageView Tutorial With Example In Android

In Android, ImageView class is used to display an image file in application. Image file is easy to use but hard to master in Android, because of the various screen sizes in Android devices. An android is enriched with some of the best UI design widgets that allows us to build good looking and attractive UI based application.

Important Note:ImageView comes with different configuration options to support different scale types. Scale type options are used for scaling the bounds of an image to the bounds of the imageview. Some of them scaleTypes configuration properties are center, center_crop, fit_xy, fitStart etc. You can read our ScaleType tutorial to learn all details on it.

Below is an ImageView code in XML:

Make sure to save lion image in drawable folder

<ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/lion" />

ImageView in Android


Table Of Contents

Attributes of ImageView:

Now let’s  we discuss some important attributes that helps us to configure a ImageView in your xml file.

1. id: id is an attribute used to uniquely identify a image view in android. Below is the example code in which we set the id of a image view.

<ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="wrap_content" />

2. src: src is an attribute used to set a source file or you can say image in your imageview to make your layout attractive.

Below is the example code in which we set the source of a imageview lion which is saved in drawable folder.

<ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/lion" /><!--set the source of an image view-->

In Java:

We can also set the source image at run time programmatically in java class. For that we use setImageResource() method as shown in below example code.

/*Add in Oncreate() funtion after setContentView()*/ ImageView simpleImageView=(ImageView) findViewById(R.id.simpleImageView); simpleImageView.setImageResource(R.drawable.lion);//set the source in java class

src attribute in imageview
3. background: background attribute is used to set the background of a ImageView. We can set a color or a drawable in the background of a ImageView.

Below is the example code in which we set the black color in the background and an image in the src attribute of image view.

<ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/lion" android:background="#000"/><!--black color in background of a image view-->

Background in ImageView Android
In Java:

We can also set the background at run time programmatically in java class. In below example code we set the black color in the background of a image view.

/*Add in Oncreate() funtion after setContentView()*/ ImageView simpleImageView=(ImageView) findViewById(R.id.simpleImageView); simpleImageView.setBackgroundColor(Color.BLACK);//set black color in background of a image view in java class

4. padding: padding attribute is used to set the padding from left, right, top or bottom of the Imageview.

  • paddingRight: set the padding from the right side of the image view.
  • paddingLeft: set the padding from the left side of the image view.
  • paddingTop: set the padding from the top side of the image view.
  • paddingBottom: set the padding from the bottom side of the image view.
  • padding: set the padding from the all side’s of the image view.

Below is the example code of padding attribute in which we set the 30dp padding from all the side’s of a image view.

<ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#000" android:src="@drawable/lion" android:padding="30dp"/><!--set 30dp padding from all the sides-->

Padding in ImageView Example
5. scaleType:scaleType is an attribute used to control how the image should be re-sized or moved to match the size of this image view. The value for scale type attribute can be fit_xy, center_crop, fitStart etc.

Below is the example code of scale type in which we set the scale type of image view to fit_xy.

<ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/lion" android:scaleType="fitXY"/><!--set scale type fit xy-->

scaleType in ImageView Example
Let’s we take an another example of scale type to understand the actual working of scale type in a image view.

In below example code we set the value for scale type “fitStart”  which is used to fit the image in the start of the image view as shown below:

<ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/lion" android:scaleType="fitStart"/><!--set scale type fit start of image view-->

scaleType fitstart in ImageView Example


Example of ImageView:

Below is the example of imageview in which we display two animal images of Lion and Monkey. And whenever user click on an image Animal name is displayed as toast on screen. Below is the final output and code:

Download Code ?

ImageView Example in Android Studio
Step 1:Create a new project and name it ImageViewExample.

In this step we create a new project in android studio by filling all the necessary details of the app like app name, package name, api versions etc.

Select File -> New -> New Project and Fill the forms and click "Finish" button.

Step 2: Download two images lion and monkey from the web. Now save those images in the drawable folder of your project.

save images in drawable folder Android Studio
Step 3: Now open res -> layout -> activity_main.xml (or) main.xml and add following code:

In this step we add the code for displaying an image view on the screen in a relative layout. Here make sure you have already saved two images name lion and monkey in your drawable folder.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <ImageView android:id="@+id/simpleImageViewLion" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="fitXY" android:src="@drawable/lion" /> <ImageView android:id="@+id/simpleImageViewMonkey" android:layout_width="fill_parent" android:layout_height="200dp" android:layout_below="@+id/simpleImageViewLion" android:layout_marginTop="10dp" android:scaleType="fitXY" android:src="@drawable/monkey" /> </RelativeLayout>

Step 4: Now open app -> java -> package -> MainActivity.java and add the following code:

In this step we add the code to initiate the image view’s and then perform click event on them.

package example.abhiandriod.imageviewexample; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView simpleImageViewLion = (ImageView) findViewById(R.id.simpleImageViewLion);//get the id of first image view ImageView simpleImageViewMonkey = (ImageView) findViewById(R.id.simpleImageViewMonkey);//get the id of second image view simpleImageViewLion.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "Lion", Toast.LENGTH_LONG).show();//display the text on image click event } }); simpleImageViewMonkey.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "Monkey", Toast.LENGTH_LONG).show();//display the text on image click event } }); } }

Output:

Now start AVD in Emulator and run the App. You will see the images of Lion and Monkey displayed on screen. Click on any Animal image and his name will appear on Screen. We clicked on Lion.

ImageView Example Run App in Android Studio



Sours: https://abhiandroid.com/ui/imageview

Working with the ImageView

Edit PagePage History

Overview

Typically, images are displayed using the built-in image view. This view takes care of the loading and optimizing of the image, freeing you to focus on app-specific details like the layout and content.

In this guide, we will take a look at how to use an ImageView, how to manipulate bitmaps, learn about the different density folders and more.

Usage

At the simplest level, an ImageView is simply a view you embed within an XML layout that is used to display an image (or any drawable) on the screen. The ImageView looks like this in :

The ImageView handles all the loading and scaling of the image for you. Note the scaleType attribute which defines how the images will be scaled to fit in your layout. In the example, using scaleType "center", the image will be displayed at its native resolution and centered in the view, regardless of how much space the view consumes.

Sizing ImageView Controls

By default, contents of an ImageView control are of a certain size -- usually the size of the image dimensions. They can also be bounded by their layout_width and layout_height attributes:

The above has been set to which sets the height and the width up or down to fit the maximum dimensions specified.

Fixing the width and height however means that the proportions of the width and height of the original image, known as the aspect ratio, will be altered. We can take advantage of the adjustViewBounds parameter to preserve this aspect ratio. However, we must either allow the height and/or width to be adjustable (i.e. by using and using for the dimension). Otherwise, the dimensions cannot be readjusted to meet the required aspect ratio.

By combining these properties together we can control the rough size of the image and still adjust the image according to the proper aspect ratio.

We can also size an at runtime within our Java source code by modifying the or inside for the view:

In certain cases, the image needs to be scaled to fit the parent view's width and the height should be adjusted proportionally. We can achieve this using an extended ResizableImageView class as described in the post.

Scale Types

An ImageView can display an image differently based on the provided. Above we discussed the type along with to match the aspect ratio of the drawable. The following is a list of all the most common types:

Scale TypeDescription
centerDisplays the image centered in the view with no scaling.
centerCropScales the image such that both the x and y dimensions are greater than or equal to the view, while maintaining the image aspect ratio; centers the image in the view.
centerInsideScales the image to fit inside the view, while maintaining the image aspect ratio. If the image is already smaller than the view, then this is the same as center.
fitCenterScales the image to fit inside the view, while maintaining the image aspect ratio. At least one axis will exactly match the view, and the result is centered inside the view.
fitStartSame as fitCenter but aligned to the top left of the view.
fitEndSame as fitCenter but aligned to the bottom right of the view.
fitXYScales the x and y dimensions to exactly match the view size; does not maintain the image aspect ratio.
matrixScales the image using a supplied Matrix class. The matrix can be supplied using the setImageMatrix method. A Matrix class can be used to apply transformations such as rotations to an image.

Note: The scale type allows you to set the exact size of the image in your layout. However, be mindful of potential distortions of the image due to scaling. If you’re creating a photo-viewing application, you will probably want to use the or scale types.

Refer to this ImageView ScaleType visual guide for additional reference. Remember that if you wish to match the aspect ratio of the actual drawable, must be declared along with not defining an explicit width and/or height.

Supporting Multiple Densities

Since Android has so many different screen sizes, resolutions and densities, there is a powerful system for selecting the correct image asset for the correct device. There are specific drawable folders for each device density category including: ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high). Notice that every app has folders for image drawables such as which is for "medium dots per inch".

To create alternative bitmap drawables for different densities, you should follow the 3:4:6:8 scaling ratio between the four generalized densities. Refer to the chart below:

DensityDPIExample DeviceScalePixels
ldpi120Galaxy Y0.75x1dp = 0.75px
mdpi160Galaxy Tab1.0x1dp = 1px
hdpi240Galaxy S II1.5x1dp = 1.5px
xhdpi320Nexus 42.0x1dp = 2px
xxhdpi480Nexus 53.0x1dp = 3px
xxxhdpi640Nexus 64.0x1dp = 4px

This means that if you generate a 100x100 for mdpi (1x baseline), then you should generate the same resource in 150x150 for hdpi (1.5x), 200x200 image for xhdpi devices (2.0x), 300x300 image for xxhdpi (3.0x) and a 75x75 image for ldpi devices (0.75x). See these density guidelines for additional details.

Densities

Final Android Resizer

To resize images more easily, check out the Final Android Resizer by downloading and running this JAR.

final resizer

This handy utility allows us to select a resources directory, choose an extra high density image and the tool will automatically generate the corresponding lower size images for us and place the subfolders inside the generated directory within the actual folder in your project as the example shows below in "Project" view (left) and the default "Android" view (right):

Refer to the screens support reference for a more detailed look at supporting a wide range of devices. Also check out the iconography guide for more details.

Mipmaps and Drawables

Starting with Android 4.3, there is now an option to use the folder to store "mipmap" images. Mipmaps are most commonly used for application icons such as the launcher icon. To learn more about the benefits of mipmaps be sure to check out the mipmapping for drawables post.

Mipmap image resources can then be accessed using the notation in place of . Placing icons in mipmap folders (rather than drawable) is considered a best practice because they can often be used at resolutions different from the device’s current density. For example, an app icon might be used on the launcher for an device. Review this post about preparing for the Nexus 6 which explains in more detail.

Working with Bitmaps

We can change the bitmap displayed in an ImageView to a drawable resource with:

or to any arbitrary bitmap with:

Scaling a Bitmap

If we need to resize a Bitmap, we can call the createScaledBitmap method to resize any bitmap to our desired width and height:

You often want to resize a bitmap but preserve the aspect ratio using a BitmapScaler utility class with code like this:

In other cases, you may want to determine the device height or width in order to resize the image accordingly. Copy this DeviceDimensionsHelper.java utility class to in your project and use anywhere that you have a context to determine the screen dimensions:

Check out this source for more information on how to scale a bitmap based instead on relative device width and height.

Note: Doing any type of scaling of images results in the loss of EXIF metadata that includes info such as camera, rotation, date/time of the photo taken. While there are workarounds to transfer this data after the image has been copied, there are current limitations. If you need this info or wish to upload it to some site, you should send the original file and not the downsampled version.

Displaying SVG Images

Android now has vector drawables support, which allows SVG files to be imported to a specific format. SVG files can be automatically converted using Android Studio by going to -> -> . Make sure to click to import the file.

Printing Bitmap Images

Android can print images using the class. The following method sends a command to the printer to print a bitmap image.

References

Sours: https://guides.codepath.com/android/Working-with-the-ImageView
  1. Burlap valance for kitchen
  2. P0299 code ford escape
  3. Jdm west coast inc

Spread the love


In android ImageView is used to display images in android application.Its hard to develop a beautiful android application without using images.In this example tutorial we will see how to implement imagview in android studio and display images in android application.

Android ImageView

Android imageView is a user interface control used to display images in android application.The images can be resource files, image urls or bitmaps.ImageView supports different scale types that scales the image bounds to imageview bounds.

Check this android UI controls tutorial to know more about UI controls.

Defining Imageview in XML(layout)

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/back"/> </LinearLayout>

Defining ImageView in JAVA

package com.codesinsider; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { private ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView image = new ImageView(this); } }

Android Imageview

android imageview

Android ImageView Supporting Multiple Device Screen Densities

In android there is a beautiful mechanism where the image is selected based on the screen density of the device.There are 5 specific directories present in res>drawable folder like drawable-mdpi, drawable-hdpi, drawable-xhdpi, drawable-xxhdpi, drawable-xxxhdpi for different device densities.For example hdpi stands for high dots per inch.

Lets see the image dimentions for different screen densities below.

mdpi – 48*48
hdpi – 72*72
xhdpi – 96*96
xxhdpi – 144*144
xxxhdpi – 192*192

Adding Images Into Resources Directory

We have to add the same image with above mentioned dimentions into their corresponding folders so that the device selects the image based on its screen density.For example if the device screen density belong to medium category it will select the image from the drawable-mdpi directory.

The same theory applies to mipmap director in res>mipmap.

android imageview multiple screen densities project structure

You can refer android’s official documentation for Screen Support and drawable Resources for more information regarding screen densities and drawable resources.

Setting Image to Imageview in XML

src attribute is used to set an image to imageview in android.Its nothing but image source.

Setting image to imageview using src attribute in XML.

<ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/back"/>

Setting Image to Imageview in JAVA

In android we can set image to imageview in different ways like from resource directory, from image url and image bitmap etc,.

Setting image to imageview from drawable folder

ImageView image = new ImageView(this); image.setImageResource(R.drawable.back);

In the above code snippets we are setting image which is present in drawable folder to imageview which means we are using local image to display in imageview

Setting imageUrl to imageview

ImageView image = new ImageView(this); image.setImageURI(Uri.parse("your image url"));

Setting imageBitmap to imageview

ImageView image = (ImageView) findViewById(R.id.image); Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.car); image.setImageBitmap(b);

Android Imageview Scaletypes

Android imageview comes with support for different scaleTypes.
scaleType attribute is used for scaling the bounds of an image to the bounds of image view.By default the scaletype is fitCenter.
Lets see the list of values for scaleType attribute.

center : Setting this value will keep the image centered in imageview without an scaling.

android imageview scaletype center

centerCrop : This value will scale the image in such a way that both X and Y dimentions are greaterthan or equal to imageview and centers the image in imageview.

android imageview scaletype center crop

centerInside : Scales the image to fit inside the imageview, while maintaining the image aspect ratio.

android imageview scaletype center inside

fitCenter : Scales the image to fit inside the imageview, while maintaining the image aspect ratio. At least one axis will exactly match the imageview, and the result is centered inside the imageview.

android imageview scaletype fitcenter

fitStart : Same as fitCenter but aligned to the top left of the view.

android imageview scaletype fitstart

fitEnd : Same as fitCenter but aligned to the bottom right of the view.

android imageview scaletype fitend

fitXY : Scales the x and y dimensions to exactly match the view size; does not maintain the image aspect ratio.

android imageview scaletype fitxy

matrix : Scales the image using a supplied Matrix class. The matrix can be supplied using the setImageMatrix method. A Matrix class can be used to apply transformations such as rotations to an image.

android imageview scaletype matrix

This brings to an end of android imageview example tutorial.We will discuss about other controls in the next posts.

Do like and share if you find this post helpful.Thank you!!


Spread the love

Naresh Pradeep

Hey there! I am the founder of CodesInsider and android developer.I love to code and build apps.

More Posts

Follow Me:

Sours: https://codesinsider.com/android-imageview/

ImageView in Android with Example

ImageView class is used to display any kind of image resource in the android application either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is a general abstraction for anything that can be drawn in Android). ImageView class or android.widget.ImageView inherits the android.view.View class which is the subclass of Kotlin.Any class. Application of ImageView is also in applying tints to an image in order to reuse a drawable resource and create overlays on background images. Moreover, ImageView is also used to control the size and movement of an image. 

Adding an ImageView to an activity

Whenever ImageView is added to an activity, it means there is a requirement for an image resource. Thus it is oblivious to provide an Image file to that ImageView class. It can be done by adding an image file that is present in the Android Studio itself or we can add our own image file. Android Studio owns a wide range of drawable resources which are very common in the android application layout. The following are the steps to add a drawable resource to the ImageView class.

Want a more fast-paced & competitive environment to learn the fundamentals of Android?

Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

Note: The steps are performed on Android Studio version 4.0

Open the activity_main.xml file in which the image is to be added 

activity.xml file in which image is to be added

Switch from code view to the design view of the activity_main.xml file. 

Design view of the activity.xml file

For adding an image from Android Studio Drag the ImageView widget to the activity area of the application, a pop-up dialogue box will open choose from the wide range of drawable resources and click “OK”. 

Adding a drawable resource to the activity

For adding an image file other than Android Studio drawable resources: 
Click on the “Resource Manager” tab on the leftmost panel and select the “Import Drawables” option. 

Select Import Drawables option to add image file

Select the path of the image file on your computer and click “OK”. After that set, the “Qualifier type” and “value” of the image file according to your need and click “Next” then “Import”. 
 

Providing value to Qualifier type for the image

Drag the ImageView class in the activity area, a pop-up dialogue box will appear which contain your imported image file. Choose your image file and click “OK”, your image will be added to the activity. 

Adding image to the activity

Note: After adding an image set its constraints layout both vertically and horizontally otherwise it will show an error.

XML Attributes of ImageView 

XML Attribute

Description

android:idTo uniquely identify an image view
android:src/app:srcCompatTo add the file path of the inserted image
android:backgroundTo provide a background color to the inserted image
android:layout_widthTo set the width of the image
android:layout_heightTo set the height of the image
android:paddingTo add padding to the image from left, right, top, or bottom of the view
android:scaleTypeTo re-size the image or to move it in order to fix its size

Example

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML

 

 

 

 

Note: All the attributes of the ImageView which are starting with app:layout_constraint are the vertical and horizontal constraints to fix the image position in the activity. This is very necessary to add the constraint to the ImageView otherwise, all the images will take the position (0, 0) of the activity layout.  

Step 4: Working with theMainActivity file

Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. Since in the activity, only 2 images have been added and nothing else is being done like touching a button, etc. So, the MainActivity file will simply look like the below code. 

Java

 

Kotlin

 

Output: 

Android activity after adding 2 images


Sours: https://www.geeksforgeeks.org/imageview-in-android-with-example/

Example android imageview

Android ImageView is used to display an image file. Android also has an . As the name suggests, the component is a button with an image on. The ImageButton is represented by the Android class android.widget.ImageButton. In this tutorial we’re going to implement both android ImageView and ImageButton in our application.

Android ImageView

Android ImageView is one of the UI widget that is used to display images in the application. It’s defined in the XML layout in the following manner.

Here is used to assign the image file from the drawable resource folder.

Android ImageView ScaleType

ImageView in android comes with different configuration options to support different scaleTypes.

scaleType options are used for scaling the bounds of an image to the bounds of image view. Below are the listed scaleType configuration properties supported.

  1. CENTER : Displays the image centered in the view with no scaling.
  2. CENTER_CROP : Scales the image such that both the x and y dimensions are greater than or equal to the view, while maintaining the image aspect ratio; centers the image in the view
  3. CENTER_INSIDE : Scales the image to fit inside the view, while maintaining the image aspect ratio. If the image is already smaller than the view, then this is the same as center
  4. FIT_CENTER : Scales the image to fit inside the view, while maintaining the image aspect ratio. At least one axis will exactly match the view, and the result is centered inside the view
  5. FIT_START : Same as fitCenter but aligned to the top left of the view
  6. FIT_END : Same as fitCenter but aligned to the bottom right of the view
  7. FIT_XY : Scales the x and y dimensions to exactly match the view size. dDoes not maintain the image aspect ratio
  8. MATRIX : Scales the image using a supplied Matrix class. The matrix can be supplied using the setImageMatrix method. A Matrix class can be used to apply transformations such as rotations to an image

The default scaleType in .

Note: The fitXY scale type allows you to set the exact size of the image in your layout. However, there can occur potential distortions of the image due to scaling. For example;

Supporting Multiple Densities in android ImageView

There is a powerful system for selecting the correct image asset for the correct device. There are specific drawable folders for each device density category including: ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high) etc. For example, a drawable-mdpi stands for drawable medium dots per inch.

In this project we’ll show various image scaleTypes in the activity along with an android Image Button.

Adding Image to Resources

We’ll use ImageView to display a “png” image. PNGs are lossless, so they have that advantage over JPG images. We add our images into folder “res/drawable-xdpi“, “res/drawable-mdpi” or “res/drawable-hdpi“ etc. depending on the size of the image.

Android ImageView, ImageButton Example Project Structure

android imageview imagebutton example project

As you can see we’ve added a balloon.png file to drawable folders of respective dimensions.

Android ImageView Project Code

The xml layout file contains five images with different scaleTypes along with an ImageButton. The layout is a child of a ScrollView (to make the activity scrollable) which we’ll discuss later.

The MainActivity.java is defined below.

Here we’ve made the second ImageView clickable to display a Toast.

Android ImageButton

Android ImageButton has all the properties of a normal button. It has the option to add a resource file instead of text.

Working with Bitmaps

Bitmaps belong to the class android.graphics.Bitmap.

Bitmapfactory is mainly used for Scaling images from the drawable. If we don’t use then it leads to insufficient memory allocations.

We can change the bitmap displayed in an ImageView to a drawable resource as it’s done for imageview2 in the code above.

The imageview5 is not assigned any scaleType so we’ve scaled it using a static method

To pass any file present in the storage into imageview the following code is implemented.

sets the bitmap content to the ImageView.

The image representing the final output is shown below:
android imageview, android imagebutton

  1. The first ImageView is not assigned any scaleType by default. Hence center being the default scaleType is implicitly assigned to it.
  2. The second ImageView has the scaleType fitXY. A distortion is seen, hence its not a good practice to use in applications.
  3. The third and fourth ImageViews have scaleType fitStart and fitEnd respectively.
  4. The fifth ImageView has been scaled with custom widths and heights using Bitmaps.

Here is a short animation of our app too.

android imageview example, android ImageButton

This brings an end to this tutorial. You can download the final Android ImageView project from the below link.

Download Android ImageView Example Project

Reference: Official Doc

Sours: https://www.journaldev.com/9474/android-imageview-imagebutton-example
Android ImageView Example

ImageView and ImageButton in Android

ImageView and ImageButton are used in Android application to place an image in the view. ImageButton is used to use an image as a button in your android application.


ImageView in Android

is used to show any picture on the user interface.

Following are some of the main attributes that are most commonly used:

AttributeDescription
Used to specify a maximum height for this view.
Used to specify a maximum width for this view.
Sets a drawable as the content for this ImageView.
Controls how the image should be resized or moved to match the size of the ImageView.
Tints the color of the image in the ImageView.

Therefore, any image that we want to display in the app should be placed under the drawable folder. This folder can be found under app → res → drawable. To insert an image, simply copy the image and then right click on drawable → Paste.

Adding picture or image to drawable


Following is the code which we need to add into the layout XML file to add an ImageView to our app screen.


ImageView in Android example


A few more, commonly used attributes with ImageView

Following are some of the commonly used attributes:

  • : This property gives a background color to your ImageView. When your image is not able to entirely fill the ImageView, then background color is used to fill the area not covered by the image.
  • : To provide padding or extra space inside the ImageView for the image.

All in ImageView

Here we have specified all the possible values for the attribute which can be used in your app for ImageView:

  • CENTER: Places the image in center, but does not scale it.
  • CENTER_CROP: Scales the image uniformly.
  • CENTER_INSIDE: This will place the image inside the container and the edges of the image will not overlap with that of the container, the image will be inside it.
  • FIT_CENTER: Scale the image from the center.
  • FIT_END: Scale the image from the end of the container, i.e from the right hand side.
  • FIT_START: Scale the image from the start of the container, i.e from the left hand side.
  • FIT_XY: This will fill the complete container with the image. This generally distorts the image by stretching/sqeezing it in disproportionate ratios.
  • MATRIX: Used to scale the image using the image matrix when drawing.

Using an Image as Button

has the same property as . Only one feature is extra, which is, images set through ImageButton are clickable, and actions can be attached with them upon clicking.

Here is how you define an ImageButton in the layout XML file:

Just like a button, the can be used to set an event listener for click event on this.



Sours: https://www.studytonight.com/android/android-imageview

Similar news:

ImageViewActivity.javapublic class ImageViewActivity extends AppCompatActivity { // Image resource id array. private int imagesIdArr[] = new int[]{R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5, R.drawable.img6}; // Current image index in imagesIdArr array. private int currImageIndex = 0; // Image transparency value.Max value is 1.0f, Min value is 0.0f. private float imageAlpha = 1.0f; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_view); // Source image view object and set default image. final ImageView imageViewSource = (ImageView)findViewById(R.id.imageViewSource); imageViewSource.setScaleType(ImageView.ScaleType.CENTER); // Set imageViewSource.setAdjustViewBounds(true); // Set default image. imageViewSource.setImageResource(imagesIdArr[currImageIndex]); // Detail image view object. final ImageView imageViewDetail = (ImageView)findViewById(R.id.imageViewDetail); // imageViewSource OnTouch Event Listener. imageViewSource.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { BitmapDrawable srcBitmap = (BitmapDrawable)imageViewSource.getDrawable(); double srcBitmapWidth = srcBitmap.getMinimumWidth(); double screenWidth = Resources.getSystem().getDisplayMetrics().widthPixels; double srcImgScale = srcBitmapWidth / screenWidth; int srcImgX = (int)(motionEvent.getX() * srcImgScale); int srcImgY = (int)(motionEvent.getY() * srcImgScale); //int srcImgX = (int)(motionEvent.getX()); //int srcImgY = (int)(motionEvent.getY()); if(srcImgX + 100 > srcBitmap.getMinimumWidth()) { srcImgX = srcBitmap.getMinimumWidth() - 100; } if(srcImgY + 100 > srcBitmap.getMinimumHeight()) { srcImgY = srcBitmap.getMinimumHeight() - 100; } Bitmap partialBitmap = Bitmap.createBitmap(srcBitmap.getBitmap(), srcImgX, srcImgY, 100, 100); imageViewDetail.setImageBitmap(partialBitmap); imageViewDetail.setAlpha(imageAlpha); return false; } }); // Next image button. Button nextImageButton = (Button)findViewById(R.id.buttonNextImage); nextImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(currImageIndex==5) { currImageIndex = -1; } currImageIndex++; imageViewSource.setImageResource(imagesIdArr[currImageIndex]); } }); // Matrix Scale button. Button matrixImageButton = (Button)findViewById(R.id.buttonMatrixImage); matrixImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageViewSource.setScaleType(ImageView.ScaleType.MATRIX); } }); // FIT_XY Scale button. Button fitXYImageButton = (Button)findViewById(R.id.buttonFitXYImage); fitXYImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageViewSource.setScaleType(ImageView.ScaleType.FIT_XY); } }); // FIT_START Scale button. Button fitStartImageButton = (Button)findViewById(R.id.buttonFitStartImage); fitStartImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageViewSource.setScaleType(ImageView.ScaleType.FIT_START); } }); // FIT_CENTER Scale button. Button fitCenterImageButton = (Button)findViewById(R.id.buttonFitCenterImage); fitCenterImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageViewSource.setScaleType(ImageView.ScaleType.FIT_CENTER); } }); // FIT_END Scale button. Button fitEndImageButton = (Button)findViewById(R.id.buttonFitEndImage); fitEndImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageViewSource.setScaleType(ImageView.ScaleType.FIT_END); } }); // CENTER Scale button. Button centerImageButton = (Button)findViewById(R.id.buttonCenterImage); centerImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageViewSource.setScaleType(ImageView.ScaleType.CENTER); } }); // CENTER_CORP Scale button. Button centerCorpImageButton = (Button)findViewById(R.id.buttonCenterCorpImage); centerCorpImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageViewSource.setScaleType(ImageView.ScaleType.CENTER_CROP); } }); // CENTER_INSIDE Scale button. Button centerInsideImageButton = (Button)findViewById(R.id.buttonCenterInsideImage); centerInsideImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { imageViewSource.setScaleType(ImageView.ScaleType.CENTER_INSIDE); } }); // Increase Image Transparency button. Button increaseImageTransparencyButton = (Button)findViewById(R.id.buttonIncreaseTransparency); increaseImageTransparencyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(imageAlpha > 1) { imageAlpha = 1; } imageAlpha += 0.1; imageViewSource.setAlpha(imageAlpha); } }); // Decrease Image Transparency button. Button decreaseImageTransparencyButton = (Button)findViewById(R.id.buttonDecreaseTransparent); decreaseImageTransparencyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(imageAlpha < 0) { imageAlpha = 0; } imageAlpha -= 0.1; imageViewSource.setAlpha(imageAlpha); } }); } }
Sours: https://www.dev2qa.com/android-imageview-examples/


4382 4383 4384 4385 4386