banner



How To Add Drawable Camera Icon In Android Studio

When you lot need to display static images in your app, y'all can utilize the Drawable class and its subclasses to draw shapes and images. A Drawable is a general brainchild for something that can exist drawn. The various subclasses help with specific image scenarios, and yous can extend them to define your own drawable objects that bear in unique means.

There are 2 ways to define and instantiate a Drawable too using the class constructors:

  • Inflate an paradigm resource (a bitmap file) saved in your project.
  • Inflate an XML resource that defines the drawable properties.

Note: You might instead adopt using a vector drawable, which defines an prototype with a set up of points, lines, and curves, forth with associated colour information. This allows vector drawables to exist scaled for different sizes without a loss of quality. For more than data, see Vector drawables overview.

Create drawables from resource images

You tin can add graphics to your app by referencing an image file from your projection resources. Supported file types are PNG (preferred), JPG (adequate), and GIF (discouraged). App icons, logos, and other graphics, such as those used in games, are well suited for this technique.

To utilise an epitome resources, add your file to the res/drawable/ directory of your project. In one case in your projection, you can reference the image resource from your code or your XML layout. Either way, information technology'south referred to using a resources ID, which is the file name without the file type extension. For example, refer to my_image.png as my_image.

Note: Image resources placed in the res/drawable/ directory may exist automatically optimized with lossless paradigm pinch by the aapt tool during the build procedure. For example, a true-color PNG that doesn't require more than 256 colors may be converted to an viii-fleck PNG with a color palette. This results in an prototype of equal quality but which requires less retention. As a result, the image binaries placed in this directory can modify at build time. If you programme on reading an image as a bitstream in order to convert information technology to a bitmap, put your images in the res/raw/ folder instead, where the aapt tool doesn't alter them.

The post-obit code snippet demonstrates how to build an ImageView that uses an image created from a drawable resources and adds it to the layout:

Kotlin

private lateinit var constraintLayout: ConstraintLayout  override fun onCreate(savedInstanceState: Package?) {     super.onCreate(savedInstanceState)      // Instantiate an ImageView and define its properties     val i = ImageView(this).apply {         setImageResource(R.drawable.my_image)         contentDescription = resource.getString(R.cord.my_image_desc)          // set 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).apply {          // 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));    // ready the ImageView bounds to match the Drawable's dimensions   i.setAdjustViewBounds(true);   i.setLayoutParams(new ViewGroup.LayoutParams(           ViewGroup.LayoutParams.WRAP_CONTENT,           ViewGroup.LayoutParams.WRAP_CONTENT));    // Add together the ImageView to the layout and set the layout as the content view.   constraintLayout.addView(i);   setContentView(constraintLayout); }            

In other cases, you lot may desire to handle your image resources every bit a Drawable object, equally shown in the following example:

Kotlin

val myImage: Drawable = ResourcesCompat.getDrawable(context.resource, R.drawable.my_image, zero)            

Coffee

Resources res = context.getResources(); Drawable myImage = ResourcesCompat.getDrawable(res, R.drawable.my_image, null);            

Warning: Each unique resource in your project tin maintain only one country, no matter how many different objects you instantiate for it. For example, if you lot instantiate ii Drawable objects from the same epitome resource and change a property (such as the alpha) for 1 object, and so it also affects the other. When dealing with multiple instances of an image resource, instead of direct transforming the Drawable object you lot should perform a tween animation.

The XML snippet below shows how to add together a drawable resources 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 information nearly using project resource, see Resources and assets.

Note: When using epitome resources every bit the source of your drawables, exist sure the images are the appropriate size for diverse pixel densities. If the images are not right they volition be scaled upward to fit, which can cause artifacting in your drawables. For more information, read Support unlike pixel densities.

Create drawables from XML resource

If there is a Drawable object that you'd similar to create, which isn't initially dependent on variables defined past your code or user interaction, and so defining the Drawable in XML is a good option. Even if yous expect your Drawable to change its properties during the user's interaction with your app, y'all should consider defining the object in XML, as you can change backdrop afterwards the object has been instantiated.

After you've defined your Drawable in XML, salvage the file in the res/drawable/ directory of your project. The following 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">     <item android:drawable="@drawable/image_expand"/>     <detail android:drawable="@drawable/image_collapse"/> </transition>        

Then, retrieve and instantiate the object by calling Resources#getDrawable() and passing the resource ID of your XML file. Any Drawable subclass that supports the inflate() method can exist defined in XML and instantiated by your app.

Each drawable course that supports XML aggrandizement 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,         zippo ) equally TransitionDrawable  val image: ImageView = findViewById(R.id.toggle_image) prototype.setImageDrawable(transition)  // Description of the initial state that the drawable represents. image.contentDescription = resources.getString(R.cord.complanate)  // And then y'all tin call the TransitionDrawable object's methods. transition.startTransition(yard)  // After the transition is consummate, modify the paradigm's content description // to reverberate the new land.            

Java

Resources res = context.getResources(); TransitionDrawable transition =     (TransitionDrawable) ResourcesCompat.getDrawable(res, R.drawable.expand_collapse, nothing);  ImageView prototype = (ImageView) findViewById(R.id.toggle_image); prototype.setImageDrawable(transition);  // Clarification of the initial state that the drawable represents. image.setContentDescription(getResources().getString(R.string.collapsed));  // And so you can call the TransitionDrawable object'southward methods. transition.startTransition(chiliad);  // Later on the transition is complete, change the image's content description // to reflect the new state.            

For more than information about the XML attributes supported, refer to the classes listed higher up.

Shape drawables

A ShapeDrawable object can be a skillful selection when you want to dynamically draw a ii-dimensional graphic. You can programmatically depict archaic shapes on a ShapeDrawable object and employ the styles that your app needs.

ShapeDrawable is a bracket of Drawable. For this reason, you can employ a ShapeDrawable wherever a Drawable is expected. For case, y'all tin use a ShapeDrawable object to set the background of a view by passing it to the setBackgroundDrawable() method of the view. You lot can also depict your shape as its own custom view and add together it to a layout in your app.

Because ShapeDrawable has its own describe() method, y'all can create a subclass of View that draws the ShapeDrawable object during the onDraw() event, as shown in the following lawmaking example:

Kotlin

class CustomDrawableView(context: Context) : View(context) {     private val drawable: ShapeDrawable = run {         val 10 = ten         val y = 10         val width = 300         val elevation = 50         contentDescription = context.resource.getString(R.string.my_view_desc)          ShapeDrawable(OvalShape()).utilise {             // If the color isn't fix, the shape uses black as the default.             paint.color = 0xff74AC23.toInt()             // If the bounds aren't set, the shape tin can't be fatigued.             setBounds(x, y, x + width, y + meridian)         }     }      override fun onDraw(sheet: Canvas) {         drawable.depict(canvass)     } }            

Java

public class CustomDrawableView extends View {   individual ShapeDrawable drawable;    public CustomDrawableView(Context context) {     super(context);      int x = 10;     int y = ten;     int width = 300;     int peak = 50;     setContentDescription(context.getResources().getString(             R.cord.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 set, the shape can't be fatigued.     drawable.setBounds(x, y, x + width, y + height);   }    protected void onDraw(Canvas sail) {     drawable.draw(canvas);   } }            

Y'all can utilize the CustomDrawableView class in the code sample higher up as you would use any other custom view. For case, you tin programmatically add together it to an activeness in your app, equally 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(Packet savedInstanceState) {   super.onCreate(savedInstanceState);   customDrawableView = new CustomDrawableView(this);    setContentView(customDrawableView); }            

If you desire to use the custom view in the XML layout instead, then 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.example.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 package, allows y'all to define various properties of the object past using public methods. Some example properties you lot might want to adjust include alpha transparency, color filter, dither, opacity, and color.

You tin can also define primitive drawable shapes using XML resources. For more information, encounter Shape drawable in Drawable resource types.

NinePatch drawables

A NinePatchDrawable graphic is a stretchable bitmap prototype that you can use every bit the background of a view. Android automatically resizes the graphic to accommodate the contents of the view. An example utilize of a NinePatch image is the groundwork used by standard Android buttons—buttons must stretch to accommodate strings of various lengths. A NinePatch graphic is a standard PNG epitome that includes an actress i-pixel border. It must be saved with the 9.png extension in the res/drawable/ directory of your project.

Use the border to define the stretchable and static areas of the image. You indicate a stretchable section by cartoon i (or more) i-pixel wide black line(s) in the left and elevation part of the border (the other edge pixels should exist fully transparent or white). You can accept every bit many stretchable sections as you want. The relative size of the stretchable sections stays the same, so the largest section e'er remains the largest.

You can also ascertain an optional drawable section of the image (effectively, the padding lines) past drawing a line on the correct and a line on the bottom. If a View object sets the NinePatch graphic as its groundwork and so specifies the view'southward text, it stretches itself and then that all the text occupies only the expanse designated by the right and bottom lines (if included). If the padding lines aren't included, Android uses the left and top lines to ascertain this drawable area.

To clarify the deviation between the lines, the left and peak lines define which pixels of the prototype are immune to be replicated in order to stretch the image. The bottom and correct lines define the relative surface area within the epitome that the contents of the view are allowed to occupy.

Effigy 1 shows an case of a NinePatch graphic used to define a push:

Image of stretchable area  and padding box

Figure 1: Example of a NinePatch graphic that defines a button

This NinePatch graphic defines one stretchable expanse with the left and top lines, and the drawable surface area with the bottom and correct lines. In the acme paradigm, the dotted grey lines identify the regions of the epitome that are replicated in gild to stretch the image. The pink rectangle in the lesser image identifies the region in which the contents of the view are allowed. If the contents don't fit in this region, then the image is stretched to make them fit.

The Draw nine-patch tool offers an extremely handy style to create your NinePatch images, using a WYSIWYG graphics editor. Information technology even raises warnings if the region you've defined for the stretchable area is at risk of producing cartoon artifacts as a issue of the pixel replication.

The following sample layout XML demonstrates how to add together a NinePatch graphic to a couple of buttons. The NinePatch epitome is saved to res/drawable/my_button_background.ix.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/big"         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"/>        

Note that the layout_width and layout_height attributes are set to wrap_content to make the button fit neatly around the text.

Figure ii shows the 2 buttons rendered from the XML and NinePatch image shown to a higher place. Notice how the width and height of the push varies with the text, and the groundwork image stretches to conform it.

Image of tiny and  normal-sized buttons

Figure 2: Buttons rendered using an XML resources and a NinePatch graphic

Custom drawables

When you want to create some custom drawings, you can exercise then by extending the Drawable class (or any of its subclasses).

The about of import method to implement is draw(Canvas) because this provides the Canvas object you must use to provide your drawing instructions.

The following code shows a elementary subclass of Drawable that draws a circle:

Kotlin

class MyDrawable : Drawable() {     private val redPaint: Pigment = Paint().apply { setARGB(255, 255, 0, 0) }      override fun draw(canvas: Sail) {         // Get the drawable's bounds         val width: Int = bounds.width()         val height: Int = premises.height()         val radius: Float = Math.min(width, height).toFloat() / 2f          // Depict a red circle in the center         sail.drawCircle((width / 2).toFloat(), (acme / 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 }            

Coffee

public class MyDrawable extends Drawable {     private final Paint redPaint;      public MyDrawable() {         // Fix color and text size         redPaint = new Paint();         redPaint.setARGB(255, 255, 0, 0);     }      @Override     public void draw(Sail canvas) {         // Get the drawable's premises         int width = getBounds().width();         int height = getBounds().height();         float radius = Math.min(width, height) / 2;          // Depict a red circle in the centre         canvas.drawCircle(width/2, pinnacle/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;     } }            

Then you tin add your drawable wherever you'd like, such as to an ImageView every bit shown here:

Kotlin

val myDrawing = MyDrawable() val epitome: ImageView = findViewById(R.id.imageView) prototype.setImageDrawable(myDrawing) image.contentDescription = resource.getString(R.string.my_image_desc)            

Java

MyDrawable mydrawing = new MyDrawable(); ImageView image = findViewById(R.id.imageView); image.setImageDrawable(mydrawing); image.setContentDescription(getResources().getString(R.string.my_image_desc));            

On Android 7.0 (API level 24) and higher, yous can also define instances of your custom drawable with XML in the following ways:

  • Using the fully-qualified class name as the XML element name. For this arroyo, the custom drawable class must be a public top-level grade:
    <com.myapp.MyDrawable xmlns:android="http://schemas.android.com/apk/res/android"     android:color="#ffff0000" />            
  • Using drawable every bit the XML tag proper noun and specifying the fully-qualified class name from the form attribute. This arroyo may be used for both public elevation-level classes and public static inner classes:
    <drawable xmlns:android="http://schemas.android.com/apk/res/android"     class="com.myapp.MyTopLevelClass$MyDrawable"     android:colour="#ffff0000" />            

Add together tint to drawables

With Android five.0 (API level 21) and above, you lot tin can tint bitmaps and nine-patches defined as alpha masks. Y'all tin can tint them with color resources or theme attributes that resolve to color resource (for instance, ?android:attr/colorPrimary). Usually, you create these assets only once and color them automatically to match your theme.

You tin use a tint to BitmapDrawable, NinePatchDrawable or VectorDrawable objects with the setTint() method. Y'all can besides set the tint color and style in your layouts with the android:tint and android:tintMode attributes.

The Android Back up Library includes the Palette class, which lets y'all excerpt prominent colors from an image. Yous can load your drawables as a Bitmap and pass information technology to Palette to access its colors. For more information, read Selecting colors with the Palette API.

Source: https://developer.android.com/guide/topics/graphics/drawables

Posted by: singletonmotheareeme.blogspot.com

0 Response to "How To Add Drawable Camera Icon In Android Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel