English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Résumé des connaissances nécessaires pour Android Drawable

What is Drawable

Firstly, Drawable is an abstract class, representing images that can be drawn on Canvas, often used as the background of a view, with multiple implementation classes to complete different functions. Secondly, Drawable can be roughly divided into these categories: images, images composed of colors. Generally defined by xml.

Inheritance system of Drawable

Implementation classes and tags of Drawable

Drawable

Obtaining internal width and height

    getIntrinsicHeight, getIntrinsicWidth
    - When the Drawable is composed of an image, the method returns the width and height of the image
    -  When the Drawable is composed of color, there is no concept of width and height, and it returns-1

Tous les Drawable et leurs utilisations

BitmapDrawable

Utilisé pour afficher une image, comme dans l'exemple suivant

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
 android:antialias="true"
 android:dither="true"
 android:filter="true"
 android:gravity="top"
 android:src="@mipmap/girl"
 android:tileMode="repeat" />

propriétés courantes

android:antialias indique si l'antialiasing est activé
android:dither indique si le débruitage est activé
android:filter indique si l'effet de filtrage est activé
android:gravity utilisé pour positionner l'image
android:src identifiant de la ressource d'image
android:tileMode mode de tiling, repeat, mirror, clamp trois

ColorDrawable

Représente une zone de dessin unicolore, qui enveloppe une couleur fixe et dessine une zone unicolore sur le canevas.

示例:

<?xml version="1.0" encoding="utf-8"?>
<color xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/colorAccent">
</color>

Peut également être créé en code

ColorDrawable drawable = new ColorDrawable(int color); //Un integer valeur de couleur est passé

NinePatchDrawable

c'est-à-dire9-patch, qui peut être étiré librement sans déformation en fonction du contenu

示例:

<?xml version="1.0" encoding="utf-8"?>
<nine-patch xmlns:android="http://schemas.android.com/apk/res/android"
 android:dither="true"
 android:filter="true"
 android:src="@color/colorAccent">
</nine-patch>

Utilisez draw9patch

dans l'image1,2La direction indique la zone de zoom dans draw9Des lignes noires sont dessinées dans le patch, et l'intersection de la longueur des lignes noires est la zone élastique
dans l'image3,4La longueur de l'intersection des lignes noires dans le patch indique la zone pouvant être remplie

ShapeDrawable

La construction de formes à partir de couleurs peut être une forme unie ou une forme avec un effet de dégradé. Les formes qui peuvent être construites incluent rectangle, oval, ring, line

Exemple de cercle avec effet de dégradé:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="oval">
 <gradient
  android:angle="45"
  android:centerColor="@color/colorAccent"
  android:centerX="50%"
  android:centerY="50%"
  android:endColor="@color/colorPrimary"
  android:gradientRadius="150dp"
  android:startColor="@color/colorPrimaryDark"
  android:type="sweep" />
 <size
  android:width="260dp"
  android:height="260dp" />
</shape>

Attention :1、la valeur de Android:angle doit être45multiples 2、oval est utilisé pour dessiner un oval, lorsqu'il est dessiné avec une largeur et une hauteur égales, il est dessiné en cercle

Exemple de cercle

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:innerRadius="100dp"
 android:shape="ring"
 android:thickness="10dp"
 android:useLevel="false" >
 <stroke
  android:width="10dp"
  android:color="@color/colorAccent" />
</shape>

Remarque :
1、android:useLevel est réglé sur false, sinon l'effet idéal ne peut pas être affiché
2、rayon interne pour le rayon interne du cercle, rayonInternalRatio pour le rapport du rayon interne par rapport à la largeur du cercle, principalement le rayon interne
3、largeur pour la largeur du cercle, largeurRatio pour le rapport de cette largeur par rapport à la largeur du cercle, principalement la largeur

propriétés courantes

- forme à dessiner pour android:shape, rectangle, oval, ring, line
- contour de forme <stroke>, a les propriétés suivantes
        - largeur de contour pour android:width
        - couleur de contour pour android:color
        - largeur de trait pour android:dashGap, largeur du trait pour dessiner une traité
        - largeur de tiret pour android:dashWidth, l'intervalle des segments de trait pour dessiner une traité (pour dessiner une traité, les deux derniers ne peuvent pas être 0)
-remplissage de couleur unie <solid>, android:color spécifie la couleur de la forme
- effet de dégradé <gradient>, ne peut pas être utilisé avec solid, a les propriétés suivantes
        - angle de dégradé pour android:angle, doit être45multiples
        - couleur de début de dégradé pour android:startColor
        - couleur de centre de dégradé pour android:centerColor
        - android:endColor Couleur de fin du dégradé
        - android:centerX Coordonnée horizontale du point central du dégradé
        - android:centerY Coordonnée verticale du point central du dégradé
        - android:gradientRadius Rayon du dégradé
        - android:type Type de dégradé, linear (linéaire), sweep (balayage), radial (radial)
- <corners> Définit les angles des quatre coins d'un rectangle (rectangle), non applicable pour d'autres shapes, avec les propriétés suivantes
        - android:topLeftRadius, android:topRightRadius, android:bottomLeftRadius, android:bottomRightRadius définissent respectivement les angles des coins supérieur gauche, supérieur droit, inférieur gauche et inférieur droit
        - android:radius Définit un angle identique pour les quatre coins, priorité faible, il peut être couvert par les quatre autres propriétés
- <size> Largeur et hauteur de la forme, correspondant à android:width et android:height
        -  shape n'a pas de largeur et de hauteur par défaut, getIntrinsicHeight et getIntrinsicWidth sont retournés-1
        -  Par size, on peut définir sa largeur et sa hauteur, mais en tant que fond de vue, il sera étiré ou rétréci pour correspondre à la taille de la vue
- <padding> Définit l'espace vide à l'intérieur de la vue contenant la forme

StateListDrawable

Peut être considéré comme un sélecteur d'état, permettant de choisir l'item correspondant pour afficher le drawable en fonction de l'état de la vue

示例:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:drawable="@color/colorPrimaryDark" android:state_pressed="false"></item>
 <item android:drawable="@color/<colorAccent" android:state_pressed="true"></item>
</selector>

États courants

android:state_pressed - Lorsque l'on appuie sur une vue, état de pression
android:state_checked - Lorsqu'une vue est sélectionnée, applicable pour CheckBox
android:state_selected - Lorsqu'une vue est sélectionnée
android:state_enabled - Lorsqu'une vue est disponible
android:state_focused - Lorsque la vue obtient le focus

LayerDeawable

LayerDeawable

示例:

<?xml version="1.0" encoding="utf-8"?>
It represents a layered collection of drawables, similar to the concept of layers in ps, multiple drawables are placed on different layers to form an overlay effect-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:drawable="@mipmap/night" />
 <item
  android:drawable="@mipmap/photo6"
  <layer />
</android:gravity="center"-list>

layer

1Attention: layer-list can contain multiple items, each item represents a drawable, and the item added later will cover the item added earlier
2By default, layer-All drawables in the list will be scaled to the size of the view, through the facility android:gravity, the scaling effect can be adjusted
3Can set the offset of top, bottom, left, and right, android:top, android:bottom, android:left, android:right

LevelListDrawable

It represents a collection of drawables, each drawable in the collection has a level, by setting different levels, LevelListDrawable can switch to different drawables. The level range is between 0~10000 between, android:maxLevel sets the maximum level, android:minLevel sets the minimum level
示例:

<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item
  android:drawable="@mipmap/photo0"
  android:maxLevel="20"
  android:minLevel="10" />
 <item
  android:drawable="@mipmap/photo1"
  android:maxLevel="40"
  android:minLevel="30" />
</level-list>

By setting the level, different Drawables can be switched, in the code

 //Change the background of ImageView to photo1, 35 In30~40 between
 iv.setImageLevel(35); 
 //Change the background of ImageView to photo0, 15In10~20 between
 iv.setImageLevel(15);

TransitionDrawable

A subclass of LayerDeawable, used to implement the fade-in and fade-out effect of two Drawables
示例:

xml file definition

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:drawable="@mipmap/night" />
 <item android:drawable="@mipmap/photo6" />
</transition>

Set the src of ImageView, in Java code

 iv = (ImageView) findViewById(R.id.iv_transition);
 drawable = (TransitionDrawable) iv.getDrawable();
 drawable.startTransition(1000); // 实现淡入淡出效果
 drawable.reverseTransition(1000);

InsetDrawable

嵌入其他Drawable,并可以在四周保留一定的间距
示例:

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
 android:drawable="@mipmap/photo6"
 android:inset="20dp">
</inset>

ScaleDrawable

根据等级将一个Drawable缩放到一定的比例,当level为0时不可见,当level为10000时无缩放效果
示例:

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
 android:drawable="@mipmap/night"
 android:scaleGravity="center"
 android:scaleHeight="50%"
 android:scaleWidth="50%" />

要显示出效果,必须设置level大于0

 iv = (ImageView) findViewById(R.id.iv_scale);
 ScaleDrawable drawable= (ScaleDrawable) iv.getDrawable();
 drawable.setLevel(1);

- android:scaleHeight="percentage",android:scaleWidth="percentage",设置宽高缩放为原来的比例为(100%-percentage)
- 设置level越大,图像显示越大

ClipDrawable

裁剪另一个Drawable,裁剪方向由android:clipOrientation和android:gravity共同决定。设置level进行裁剪,level的大小从0到10000, when level is 0, it will not be displayed at all, and when level is10000 will be fully displayed
xml definition

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
 android:clipOrientation="horizontal"
 android:drawable="@mipmap/night"
 android:gravity="right"></clip>
 <ImageView
  android:id="@"+id/iv_clip"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:src="@drawable/drawable_clip" />

Cut through setting level

 ImageView iv = (ImageView) findViewById(R.id.iv_clip);
 ClipDrawable drawable= (ClipDrawable) iv.getDrawable();
 drawable.setLevel(5000); // The larger the level set, the smaller the cutting range

Properties

android:clipOrientation, horizontal cutting in the horizontal direction, vertical cutting in the vertical direction
android:gravity, combined with the cutting direction

Custom Drawable

Custom circular Drawable

package com.yu.drawablelearing;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
public class CircleDrawable extends Drawable{
 private int radius;
 private int mWidth;
 private int mHeight;
 private Paint mPaint;
 @Override
 public void draw(Canvas canvas) {
  canvas.drawCircle(mWidth/2,mHeight/2,radius,mPaint);
 }
 public CircleDrawable(Bitmap bitmap) {
  radius = Math.min(bitmap.getWidth(), bitmap.getHeight());/2;
  mWidth = bitmap.getWidth();
  mHeight = bitmap.getHeight();
  BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
  mPaint = new Paint();
  mPaint.setShader(bitmapShader);
  mPaint.setAntiAlias(true);
 }
 @Override
 public void setAlpha(int alpha) {
  mPaint.setAlpha(alpha);
  invalidateSelf();
 }
 @Override
 public void setColorFilter(ColorFilter colorFilter) {
  mPaint.setColorFilter(colorFilter);
  invalidateSelf();
 }
 @Override
 public int getOpacity() {
  return PixelFormat.TRANSLUCENT;
 }
 @Override
 public int getIntrinsicHeight() {
  return mHeight;
 }
 @Override
 public int getIntrinsicWidth() {
  return mWidth;
 }
}

Custom rounded rectangle Drawable

package com.yu.drawablelearing;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
/**
 * Created by pecu on 2016/08/24.
 */
public class RoundRectangleDrawable extends Drawable {
 private RectF rectF;
 private Paint mPaint;
 Bitmap mBitmap;
 @Override
 public void draw(Canvas canvas) {
  canvas.drawRoundRect(rectF, mBitmap.getWidth()/6,mBitmap.getHeight()/6, mPaint);
 }
 public RoundRectangleDrawable(Bitmap bitmap) {
  mBitmap = bitmap;
  mPaint = new Paint();
  BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
  mPaint.setAntiAlias(true);
  mPaint.setShader(bitmapShader);
 }
 @Override
 public void setAlpha(int alpha) {
  mPaint.setAlpha(alpha);
  invalidateSelf();
 }
 @Override
 public void setColorFilter(ColorFilter colorFilter) {
  mPaint.setColorFilter(colorFilter);
  invalidateSelf();
 }
 @Override
 public void setBounds(int left, int top, int right, int bottom) {
  super.setBounds(left, top, right, bottom);
  rectF = new RectF(left, top, right, bottom);
 }
 @Override
 public int getOpacity() {
  return PixelFormat.TRANSLUCENT;
 }
 @Override
 public int getIntrinsicWidth() {
  return mBitmap.getWidth();
 }
 @Override
 public int getIntrinsicHeight() {
  return mBitmap.getHeight();
 }
}

Les étapes générales de la création d'un Drawable personnalisé

 1La classe Drawable personnalisée hérite de Drawable
 2Les méthodes telles que getOpacity, setColorFilter, setAlpha doivent être réalisées
 3Le dessin est effectué dans la méthode onDraw
 4Si le Drawable personnalisé a une taille fixe, il faut réaliser les méthodes getIntrinsicWidth, getIntrinsicHeight

C'est tout le contenu de cet article, j'espère que cela aidera à votre apprentissage, et j'espère que vous soutiendrez également le tutoriel criant.

Déclaration : le contenu de cet article est来源于网络,à l'origine des droits d'auteur appartiennent à leurs propriétaires respectifs, le contenu est contribué par les utilisateurs d'Internet et téléchargé eux-mêmes, ce site Web ne possède pas de propriété, n'a pas été traité par l'édition humaine et n'assume pas de responsabilité juridique pertinente. Si vous trouvez du contenu suspect de violation des droits d'auteur, veuillez envoyer un e-mail à : notice#w3Déclaration : le contenu de cet article est来源于网络,à l'origine des droits d'auteur appartiennent à leurs propriétaires respectifs, le contenu est contribué par les utilisateurs d'Internet et téléchargé eux-mêmes, ce site Web ne possède pas de propriété, n'a pas été traité par l'édition humaine et n'assume pas de responsabilité juridique pertinente. Si vous trouvez du contenu suspect de violation des droits d'auteur, veuillez envoyer un e-mail à : notice#w

Vous pourriez aussi aimer