How To Set Image As Background In Android
When you need to display static images in your app, yous can apply the Drawable
class and its subclasses to draw shapes and images. A Drawable
is a general abstraction for something that tin exist fatigued. The various subclasses assist with specific prototype scenarios, and you tin extend them to define your own drawable objects that behave in unique ways.
There are two ways to ascertain and instantiate a Drawable
as well using the grade constructors:
- Inflate an image resources (a bitmap file) saved in your project.
- Inflate an XML resource that defines the drawable properties.
Notation: You might instead prefer using a vector drawable, which defines an epitome with a set of points, lines, and curves, forth with associated colour information. This allows vector drawables to be scaled for unlike sizes without a loss of quality. For more than information, encounter Vector drawables overview.
Create drawables from resource images
Y'all tin add graphics to your app by referencing an image file from your project resource. Supported file types are PNG (preferred), JPG (acceptable), and GIF (discouraged). App icons, logos, and other graphics, such equally those used in games, are well suited for this technique.
To use an epitome resource, add together your file to the res/drawable/
directory of your project. In one case in your project, you lot can reference the epitome resource from your code or your XML layout. Either style, it's referred to using a resource ID, which is the file name without the file type extension. For example, refer to my_image.png
as my_image
.
Note: Paradigm resource placed in the res/drawable/
directory may be automatically optimized with lossless image compression by the aapt
tool during the build process. For example, a truthful-color PNG that doesn't require more than than 256 colors may be converted to an 8-scrap PNG with a color palette. This results in an image of equal quality but which requires less retention. As a result, the image binaries placed in this directory can modify at build time. If y'all program on reading an image as a bitstream in order to convert it to a bitmap, put your images in the res/raw/
binder instead, where the aapt
tool doesn't change them.
The following code snippet demonstrates how to build an ImageView
that uses an image created from a drawable resource and adds it to the layout:
Kotlin
private lateinit var constraintLayout: ConstraintLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Instantiate an ImageView and define its properties val i = ImageView(this).apply { setImageResource(R.drawable.my_image) contentDescription = resource.getString(R.string.my_image_desc) // prepare the ImageView bounds to match the Drawable's dimensions adjustViewBounds = true layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) } // Create a ConstraintLayout in which to add the ImageView constraintLayout = ConstraintLayout(this).employ { // Add the ImageView to the layout. addView(i) } // Set the layout as the content view. setContentView(constraintLayout) }
Java
ConstraintLayout constraintLayout; protected void onCreate(Package savedInstanceState) { super.onCreate(savedInstanceState); // Create a ConstraintLayout in which to add the ImageView constraintLayout = new ConstraintLayout(this); // Instantiate an ImageView and define its properties ImageView i = new ImageView(this); i.setImageResource(R.drawable.my_image); i.setContentDescription(getResources().getString(R.string.my_image_desc)); // set up the ImageView bounds to friction match the Drawable'south dimensions i.setAdjustViewBounds(true); i.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); // Add the ImageView to the layout and prepare the layout as the content view. constraintLayout.addView(i); setContentView(constraintLayout); }
In other cases, you may want to handle your image resources every bit a Drawable
object, equally shown in the following example:
Kotlin
val myImage: Drawable = ResourcesCompat.getDrawable(context.resources, R.drawable.my_image, null)
Coffee
Resources res = context.getResources(); Drawable myImage = ResourcesCompat.getDrawable(res, R.drawable.my_image, null);
Warning: Each unique resource in your projection can maintain only 1 land, no thing how many different objects you lot instantiate for it. For example, if y'all instantiate ii Drawable
objects from the aforementioned image resources and change a property (such as the alpha) for ane object, then it likewise affects the other. When dealing with multiple instances of an epitome resource, instead of direct transforming the Drawable
object you should perform a tween animation.
The XML snippet below shows how to add a drawable resource to an ImageView
in the XML layout:
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/my_image" android:contentDescription="@string/my_image_desc" />
For more than data about using project resources, come across Resources and assets.
Notation: When using image resource as the source of your drawables, be certain the images are the appropriate size for diverse pixel densities. If the images are not right they will exist scaled upward to fit, which tin can cause artifacting in your drawables. For more information, read Back up dissimilar pixel densities.
Create drawables from XML resource
If there is a Drawable
object that you'd like to create, which isn't initially dependent on variables defined by your code or user interaction, and so defining the Drawable
in XML is a good selection. Even if you expect your Drawable
to change its properties during the user'south interaction with your app, you should consider defining the object in XML, as you can change properties afterward the object has been instantiated.
After yous've divers your Drawable
in XML, save the file in the res/drawable/
directory of your projection. The post-obit example shows the XML that defines a TransitionDrawable
resource, which inherits from Drawable
:
<!-- res/drawable/expand_collapse.xml --> <transition xmlns:android="http://schemas.android.com/apk/res/android"> <detail android:drawable="@drawable/image_expand"/> <item android:drawable="@drawable/image_collapse"/> </transition>
Then, retrieve and instantiate the object past calling Resources#getDrawable()
and passing the resource ID of your XML file. Whatever Drawable
subclass that supports the inflate()
method tin can be defined in XML and instantiated by your app.
Each drawable class that supports XML inflation utilizes specific XML attributes that help define the object properties. The following code instantiates the TransitionDrawable
and sets it equally the content of an ImageView
object:
Kotlin
val transition= ResourcesCompat.getDrawable( context.resources, R.drawable.expand_collapse, nada ) as TransitionDrawable val epitome: ImageView = findViewById(R.id.toggle_image) prototype.setImageDrawable(transition) // Clarification of the initial country that the drawable represents. epitome.contentDescription = resources.getString(R.string.collapsed) // And then you tin phone call the TransitionDrawable object'due south methods. transition.startTransition(1000) // After the transition is complete, modify the image'southward content description // to reverberate the new state.
Java
Resource res = context.getResources(); TransitionDrawable transition = (TransitionDrawable) ResourcesCompat.getDrawable(res, R.drawable.expand_collapse, zippo); ImageView image = (ImageView) findViewById(R.id.toggle_image); epitome.setImageDrawable(transition); // Description of the initial state that the drawable represents. prototype.setContentDescription(getResources().getString(R.cord.collapsed)); // Then yous can call the TransitionDrawable object's methods. transition.startTransition(1000); // Afterwards the transition is complete, alter the paradigm's content description // to reflect the new land.
For more information about the XML attributes supported, refer to the classes listed above.
Shape drawables
A ShapeDrawable
object can exist a good option when you want to dynamically draw a two-dimensional graphic. You tin can programmatically depict primitive shapes on a ShapeDrawable
object and apply the styles that your app needs.
ShapeDrawable
is a subclass of Drawable
. For this reason, y'all tin can use a ShapeDrawable
wherever a Drawable
is expected. For example, yous can use a ShapeDrawable
object to set the background of a view past passing information technology to the setBackgroundDrawable()
method of the view. You lot can also describe your shape every bit its ain custom view and add it to a layout in your app.
Because ShapeDrawable
has its own draw()
method, you can create a subclass of View
that draws the ShapeDrawable
object during the onDraw()
consequence, as shown in the following lawmaking example:
Kotlin
form CustomDrawableView(context: Context) : View(context) { private val drawable: ShapeDrawable = run { val x = ten val y = x val width = 300 val height = 50 contentDescription = context.resources.getString(R.string.my_view_desc) ShapeDrawable(OvalShape()).use { // If the color isn't prepare, the shape uses black every bit the default. paint.color = 0xff74AC23.toInt() // If the premises aren't gear up, the shape can't be drawn. setBounds(10, y, 10 + width, y + height) } } override fun onDraw(canvass: Canvas) { drawable.describe(canvas) } }
Java
public class CustomDrawableView extends View { individual ShapeDrawable drawable; public CustomDrawableView(Context context) { super(context); int x = x; int y = 10; int width = 300; int meridian = 50; setContentDescription(context.getResources().getString( R.string.my_view_desc)); drawable = new ShapeDrawable(new OvalShape()); // If the color isn't set, the shape uses black as the default. drawable.getPaint().setColor(0xff74AC23); // If the bounds aren't gear up, the shape tin can't be drawn. drawable.setBounds(10, y, x + width, y + pinnacle); } protected void onDraw(Canvas sheet) { drawable.describe(canvass); } }
Yous can apply the CustomDrawableView
form in the code sample in a higher place as yous would use whatsoever other custom view. For instance, you can programmatically add together it to an activity in your app, as shown in the following example:
Kotlin
private lateinit var customDrawableView: CustomDrawableView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) customDrawableView = CustomDrawableView(this) setContentView(customDrawableView) }
Java
CustomDrawableView customDrawableView; protected void onCreate(Parcel savedInstanceState) { super.onCreate(savedInstanceState); customDrawableView = new CustomDrawableView(this); setContentView(customDrawableView); }
If you want to use the custom view in the XML layout instead, so the CustomDrawableView
grade must override the View(Context, AttributeSet)
constructor, which is called when the class is inflated from XML. The following example shows how to declare the CustomDrawableView
in the XML layout:
<com.instance.shapedrawable.CustomDrawableView android:layout_width="fill_parent" android:layout_height="wrap_content" />
The ShapeDrawable
course, like many other drawable types in the android.graphics.drawable
parcel, allows you to define various backdrop of the object by using public methods. Some instance properties yous might want to adjust include alpha transparency, color filter, dither, opacity, and color.
Yous tin can also define primitive drawable shapes using XML resources. For more than information, encounter Shape drawable in Drawable resource types.
NinePatch drawables
A NinePatchDrawable
graphic is a stretchable bitmap image that you can utilize as the background of a view. Android automatically resizes the graphic to accommodate the contents of the view. An example apply of a NinePatch image is the background used by standard Android buttons—buttons must stretch to accommodate strings of diverse lengths. A NinePatch graphic is a standard PNG image that includes an actress 1-pixel border. It must be saved with the ix.png
extension in the res/drawable/
directory of your project.
Utilize the border to define the stretchable and static areas of the image. You point a stretchable section past drawing one (or more) 1-pixel wide black line(due south) in the left and top part of the edge (the other border pixels should be fully transparent or white). Yous can have as many stretchable sections as yous want. The relative size of the stretchable sections stays the same, so the largest section always remains the largest.
Y'all can also define an optional drawable department of the image (effectively, the padding lines) past drawing a line on the right and a line on the bottom. If a View
object sets the NinePatch graphic equally its groundwork and and so specifies the view's text, information technology stretches itself then that all the text occupies but the surface area designated past the right and bottom lines (if included). If the padding lines aren't included, Android uses the left and top lines to define this drawable area.
To clarify the difference between the lines, the left and top lines define which pixels of the image are allowed to be replicated in order to stretch the image. The lesser and right lines define the relative area within the prototype that the contents of the view are immune to occupy.
Figure i shows an example of a NinePatch graphic used to define a push:
This NinePatch graphic defines 1 stretchable area with the left and top lines, and the drawable area with the lesser and right lines. In the acme image, the dotted greyness lines identify the regions of the image that are replicated in society to stretch the paradigm. The pink rectangle in the bottom image identifies the region in which the contents of the view are allowed. If the contents don't fit in this region, and then the prototype is stretched to make them fit.
The Draw nine-patch tool offers an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. It even raises warnings if the region you've divers for the stretchable area is at risk of producing drawing artifacts as a result of the pixel replication.
The following sample layout XML demonstrates how to add a NinePatch graphic to a couple of buttons. The NinePatch prototype is saved to res/drawable/my_button_background.9.png
.
<Button android:id="@+id/tiny" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerInParent="true" android:text="Tiny" android:textSize="8sp" android:background="@drawable/my_button_background"/> <Button android:id="@+id/large" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerInParent="true" android:text="Biiiiiiig text!" android:textSize="30sp" android:background="@drawable/my_button_background"/>
Annotation that the layout_width
and layout_height
attributes are set to wrap_content
to make the push button fit neatly effectually the text.
Figure 2 shows the 2 buttons rendered from the XML and NinePatch image shown to a higher place. Find how the width and height of the button varies with the text, and the background image stretches to conform it.
Custom drawables
When yous want to create some custom drawings, you can do so by extending the Drawable
form (or any of its subclasses).
The near important method to implement is draw(Canvas)
because this provides the Canvas
object yous must utilise to provide your drawing instructions.
The following lawmaking shows a uncomplicated subclass of Drawable
that draws a circle:
Kotlin
class MyDrawable : Drawable() { private val redPaint: Pigment = Pigment().apply { setARGB(255, 255, 0, 0) } override fun depict(canvas: Canvas) { // Get the drawable's premises val width: Int = bounds.width() val height: Int = premises.height() val radius: Float = Math.min(width, height).toFloat() / 2f // Describe a reddish circle in the center sheet.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), radius, redPaint) } override fun setAlpha(alpha: Int) { // This method is required } override fun setColorFilter(colorFilter: ColorFilter?) { // This method is required } override fun getOpacity(): Int = // Must be PixelFormat.UNKNOWN, TRANSLUCENT, TRANSPARENT, or OPAQUE PixelFormat.OPAQUE }
Java
public form MyDrawable extends Drawable { private final Pigment redPaint; public MyDrawable() { // Set colour and text size redPaint = new Paint(); redPaint.setARGB(255, 255, 0, 0); } @Override public void draw(Canvas sheet) { // Get the drawable's bounds int width = getBounds().width(); int height = getBounds().height(); float radius = Math.min(width, elevation) / 2; // Draw a red circumvolve in the center canvas.drawCircle(width/2, top/2, radius, redPaint); } @Override public void setAlpha(int alpha) { // This method is required } @Override public void setColorFilter(ColorFilter colorFilter) { // This method is required } @Override public int getOpacity() { // Must exist PixelFormat.UNKNOWN, TRANSLUCENT, TRANSPARENT, or OPAQUE return PixelFormat.OPAQUE; } }
And then y'all tin add your drawable wherever you lot'd like, such as to an ImageView
as shown hither:
Kotlin
val myDrawing = MyDrawable() val image: ImageView = findViewById(R.id.imageView) image.setImageDrawable(myDrawing) image.contentDescription = resources.getString(R.string.my_image_desc)
Coffee
MyDrawable mydrawing = new MyDrawable(); ImageView image = findViewById(R.id.imageView); image.setImageDrawable(mydrawing); epitome.setContentDescription(getResources().getString(R.cord.my_image_desc));
On Android 7.0 (API level 24) and higher, you can besides define instances of your custom drawable with XML in the following means:
- Using the fully-qualified class proper name as the XML element name. For this approach, the custom drawable class must be a public top-level class:
<com.myapp.MyDrawable xmlns:android="http://schemas.android.com/apk/res/android" android:colour="#ffff0000" />
- Using
drawable
as the XML tag proper name and specifying the fully-qualified course name from the class attribute. This approach may exist used for both public top-level classes and public static inner classes:<drawable xmlns:android="http://schemas.android.com/apk/res/android" course="com.myapp.MyTopLevelClass$MyDrawable" android:colour="#ffff0000" />
Add tint to drawables
With Android 5.0 (API level 21) and to a higher place, you tin can tint bitmaps and nine-patches defined every bit alpha masks. You can tint them with color resources or theme attributes that resolve to color resource (for example, ?android:attr/colorPrimary
). Usually, you lot create these assets only once and colour them automatically to friction match your theme.
You tin can use a tint to BitmapDrawable
, NinePatchDrawable
or VectorDrawable
objects with the setTint()
method. You can likewise set the tint colour and mode in your layouts with the android:tint
and android:tintMode
attributes.
The Android Support Library includes the Palette
class, which lets you excerpt prominent colors from an prototype. You can load your drawables as a Bitmap
and pass it to Palette
to admission its colors. For more data, read Selecting colors with the Palette API.
How To Set Image As Background In Android,
Source: https://developer.android.com/guide/topics/graphics/drawables
Posted by: kleinrepasustem1946.blogspot.com
0 Response to "How To Set Image As Background In Android"
Post a Comment