Skip to content Skip to sidebar Skip to footer

drawing 3d objects in android

When you demand to display static images in your app, you lot tin can use the Drawable class and its subclasses to draw shapes and images. A Drawable is a general abstraction for something that can be drawn. The various subclasses assist with specific paradigm scenarios, and you tin extend them to define your ain drawable objects that behave in unique means.

There are two ways to ascertain and instantiate a Drawable besides using the form constructors:

  • Inflate an image resource (a bitmap file) saved in your projection.
  • Inflate an XML resources that defines the drawable properties.

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

Create drawables from resources images

Yous can add graphics to your app by referencing an paradigm file from your project 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 use an prototype resource, add your file to the res/drawable/ directory of your projection. Once in your project, you lot can reference the image resource from your code or your XML layout. Either manner, it'southward referred to using a resource ID, which is the file proper noun 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 be automatically optimized with lossless image compression by the aapt tool during the build process. For example, a true-color PNG that doesn't crave more than 256 colors may be converted to an 8-chip PNG with a color palette. This results in an image of equal quality but which requires less retentiveness. As a result, the image binaries placed in this directory can modify at build time. If you plan on reading an epitome every bit 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 modify 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

individual lateinit var constraintLayout: ConstraintLayout  override fun onCreate(savedInstanceState: Package?) {     super.onCreate(savedInstanceState)      // Instantiate an ImageView and define its backdrop     val i = ImageView(this).apply {         setImageResource(R.drawable.my_image)         contentDescription = resources.getString(R.cord.my_image_desc)          // set the ImageView bounds to lucifer the Drawable's dimensions         adjustViewBounds = truthful         layoutParams = ViewGroup.LayoutParams(                 ViewGroup.LayoutParams.WRAP_CONTENT,                 ViewGroup.LayoutParams.WRAP_CONTENT)     }      // Create a ConstraintLayout in which to add the ImageView     constraintLayout = ConstraintLayout(this).use {          // Add the ImageView to the layout.         addView(i)     }      // Set the layout equally the content view.     setContentView(constraintLayout) }            

Java

ConstraintLayout constraintLayout;  protected void onCreate(Parcel 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.cord.my_image_desc));    // set the ImageView bounds to friction match the Drawable'due 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 set the layout as the content view.   constraintLayout.addView(i);   setContentView(constraintLayout); }            

In other cases, you may desire to handle your image resource every bit a Drawable object, as shown in the following instance:

Kotlin

val myImage: Drawable = ResourcesCompat.getDrawable(context.resources, R.drawable.my_image, nix)            

Java

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

Warning: Each unique resource in your projection can maintain only one country, no affair how many unlike objects yous instantiate for information technology. For example, if y'all instantiate two Drawable objects from the aforementioned image resource and change a property (such equally the blastoff) for one object, so it also affects the other. When dealing with multiple instances of an paradigm resource, instead of straight transforming the Drawable object you lot 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 information about using projection resource, see Resources and assets.

Notation: When using image resources as the source of your drawables, be sure the images are the appropriate size for various pixel densities. If the images are non correct they will be scaled up to fit, which can cause artifacting in your drawables. For more than information, read Support dissimilar pixel densities.

Create drawables from XML resource

If in that location is a Drawable object that y'all'd like to create, which isn't initially dependent on variables defined past your code or user interaction, then defining the Drawable in XML is a good option. Even if y'all expect your Drawable to change its properties during the user's interaction with your app, you should consider defining the object in XML, every bit you can alter properties after the object has been instantiated.

After you've defined your Drawable in XML, save the file in the res/drawable/ directory of your project. The post-obit example shows the XML that defines a TransitionDrawable resources, which inherits from Drawable:

<!-- res/drawable/expand_collapse.xml --> <transition xmlns:android="http://schemas.android.com/apk/res/android">     <particular android:drawable="@drawable/image_expand"/>     <item android:drawable="@drawable/image_collapse"/> </transition>        

Then, call back and instantiate the object by calling Resources#getDrawable() and passing the resource ID of your XML file. Any Drawable bracket that supports the inflate() method can be defined in XML and instantiated past 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 every bit the content of an ImageView object:

Kotlin

val transition= ResourcesCompat.getDrawable(         context.resources,         R.drawable.expand_collapse,         null ) as TransitionDrawable  val image: ImageView = findViewById(R.id.toggle_image) image.setImageDrawable(transition)  // Clarification of the initial land that the drawable represents. image.contentDescription = resources.getString(R.string.collapsed)  // And so you tin can phone call the TransitionDrawable object'southward methods. transition.startTransition(1000)  // Later the transition is complete, alter the paradigm's content description // to reflect the new land.            

Coffee

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

For more information near the XML attributes supported, refer to the classes listed above.

Shape drawables

A ShapeDrawable object can be a good option when you want to dynamically draw a two-dimensional graphic. You can programmatically draw primitive shapes on a ShapeDrawable object and utilise the styles that your app needs.

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

Because ShapeDrawable has its own draw() method, you tin can create a subclass of View that draws the ShapeDrawable object during the onDraw() event, equally shown in the following code example:

Kotlin

form CustomDrawableView(context: Context) : View(context) {     private val drawable: ShapeDrawable = run {         val x = x         val y = 10         val width = 300         val superlative = 50         contentDescription = context.resources.getString(R.string.my_view_desc)          ShapeDrawable(OvalShape()).apply {             // If the color isn't set, the shape uses blackness every bit the default.             paint.color = 0xff74AC23.toInt()             // If the bounds aren't set, the shape tin can't be drawn.             setBounds(x, y, x + width, y + meridian)         }     }      override fun onDraw(sail: Canvass) {         drawable.draw(canvas)     } }            

Java

public course CustomDrawableView extends View {   private ShapeDrawable drawable;    public CustomDrawableView(Context context) {     super(context);      int x = 10;     int y = 10;     int width = 300;     int superlative = 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 equally the default.     drawable.getPaint().setColor(0xff74AC23);     // If the bounds aren't set up, the shape can't be drawn.     drawable.setBounds(x, y, ten + width, y + superlative);   }    protected void onDraw(Canvas canvas) {     drawable.draw(canvas);   } }            

Y'all can employ the CustomDrawableView class in the code sample to a higher place equally you would utilise whatever other custom view. For example, y'all tin programmatically add information technology to an activity in your app, as shown in the post-obit case:

Kotlin

individual lateinit var customDrawableView: CustomDrawableView  override fun onCreate(savedInstanceState: Packet?) {     super.onCreate(savedInstanceState)     customDrawableView = CustomDrawableView(this)      setContentView(customDrawableView) }            

Java

CustomDrawableView customDrawableView;  protected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   customDrawableView = new CustomDrawableView(this);    setContentView(customDrawableView); }            

If you want to employ the custom view in the XML layout instead, then the CustomDrawableView class must override the View(Context, AttributeSet) constructor, which is called when the course is inflated from XML. The post-obit 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 class, similar many other drawable types in the android.graphics.drawable parcel, allows you lot to ascertain various properties of the object by using public methods. Some example properties you might want to adjust include alpha transparency, colour filter, dither, opacity, and color.

Yous can also define primitive drawable shapes using XML resources. For more information, come across Shape drawable in Drawable resource types.

NinePatch drawables

A NinePatchDrawable graphic is a stretchable bitmap image that you can use equally the background of a view. Android automatically resizes the graphic to accommodate the contents of the view. An instance use 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 extra 1-pixel border. Information technology must exist 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 drawing 1 (or more) i-pixel wide black line(s) in the left and superlative part of the border (the other edge pixels should be fully transparent or white). Y'all can have equally many stretchable sections as you want. The relative size of the stretchable sections stays the aforementioned, and then the largest section always remains the largest.

You tin also define an optional drawable department of the image (effectively, the padding lines) by drawing a line on the right and a line on the bottom. If a View object sets the NinePatch graphic as its background and then specifies the view's text, it stretches itself so that all the text occupies only the surface area designated by 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 epitome are allowed to be replicated in order to stretch the prototype. The bottom and right lines define the relative area inside the prototype that the contents of the view are allowed to occupy.

Effigy 1 shows an example of a NinePatch graphic used to define a button:

Image of stretchable area  and padding box

Figure 1: Instance of a NinePatch graphic that defines a push button

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

The Draw 9-patch tool offers an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. Information technology fifty-fifty raises warnings if the region you've divers for the stretchable area is at take chances of producing cartoon artifacts every bit 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 paradigm 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/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:groundwork="@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.

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

Image of tiny and  normal-sized buttons

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

Custom drawables

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

The nigh important method to implement is describe(Canvas) because this provides the Canvas object you must use to provide your cartoon instructions.

The following code shows a simple bracket of Drawable that draws a circle:

Kotlin

class MyDrawable : Drawable() {     private val redPaint: Paint = Paint().apply { setARGB(255, 255, 0, 0) }      override fun depict(sheet: Sheet) {         // Become the drawable's bounds         val width: Int = premises.width()         val pinnacle: Int = bounds.height()         val radius: Float = Math.min(width, height).toFloat() / 2f          // Draw a red circle in the middle         canvas.drawCircle((width / 2).toFloat(), (tiptop / 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 grade MyDrawable extends Drawable {     private final Paint redPaint;      public MyDrawable() {         // Set up color and text size         redPaint = new Paint();         redPaint.setARGB(255, 255, 0, 0);     }      @Override     public void draw(Sail canvas) {         // Get the drawable's bounds         int width = getBounds().width();         int height = getBounds().elevation();         float radius = Math.min(width, summit) / 2;          // Describe a red circumvolve in the center         canvas.drawCircle(width/two, height/two, radius, redPaint);     }      @Override     public void setAlpha(int blastoff) {         // This method is required     }      @Override     public void setColorFilter(ColorFilter colorFilter) {         // This method is required     }      @Override     public int getOpacity() {         // Must be PixelFormat.UNKNOWN, TRANSLUCENT, TRANSPARENT, or OPAQUE         return PixelFormat.OPAQUE;     } }            

And so yous can add your drawable wherever you'd like, such as to an ImageView as shown here:

Kotlin

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

Java

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

On Android 7.0 (API level 24) and higher, y'all can as well define instances of your custom drawable with XML in the following means:

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

Add tint to drawables

With Android 5.0 (API level 21) and above, you can tint bitmaps and nine-patches divers every bit blastoff masks. Y'all can tint them with color resources or theme attributes that resolve to color resource (for instance, ?android:attr/colorPrimary). Normally, you create these avails only once and color them automatically to lucifer your theme.

Yous tin can utilise a tint to BitmapDrawable, NinePatchDrawable or VectorDrawable objects with the setTint() method. You can also set the tint color and style in your layouts with the android:tint and android:tintMode attributes.

The Android Support Library includes the Palette class, which lets you extract prominent colors from an image. You can load your drawables as a Bitmap and pass it to Palette to admission its colors. For more than information, read Selecting colors with the Palette API.

larayebere.blogspot.com

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

แสดงความคิดเห็น for "drawing 3d objects in android"