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

Android Drawable 필수 지식 요약

Drawable는 무엇인가요

먼저 Drawable는 추상 클래스로, Canvas에서 그릴 수 있는 이미지를 나타내며, 대부분 View의 배경으로 사용되며, 다양한 구현 클래스가 다양한 기능을 수행합니다. 또한 Drawable는 대략 다음과 같은 분류로 나눌 수 있습니다: 이미지, 색상으로 구성된 이미지. 일반적으로 xml에서 정의됩니다.

Drawable의 상속 체계

Drawable의 구현 클래스 및 태그

Drawable

내부 너비와 높이의 획득

    getIntrinsicHeight, getIntrinsicWidth
    - Drawable가 이미지로 구성되어 있을 때 메서드가 반환하는 것은 이미지의 너비와 높이입니다
    -  Drawable가 색상으로 구성되어 있을 때 너비와 높이 개념이 없으며 반환됩니다-1

모든 Drawable 및 사용 방법

BitmapDrawable

이미지를 표시하는 데 사용되며, 다음 예제와 같습니다

<?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" />

常用属性

android:antialias 안티 앵글스 사용 여부
android:dither防충격 사용 여부
android:filter 필터 효과 사용 여부
android:gravity 이미지에 대한 위치 설정
android:src 이미지 자원 id
android:tileMode 타일링 모드, repeat, mirror, clamp 세 가지

ColorDrawable

단색으로 그릴 수 있는 영역을 나타내며, 고정된 색상을 포장한 것입니다. 캔버스에 단색의 영역을 그립니다

예제:

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

또한 코드로 생성할 수 있습니다

ColorDrawable drawable = new ColorDrawable(int color); //color의 integer 값을 입력합니다

NinePatchDrawable

즉9-patch 그림은 내용에 따라 자유롭게 확장하고 축소할 수 있으며, 변형 없이 확장할 수 있습니다

예제:

<?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>

draw9patch에서 확대 영역을 설정합니다

그림에서1、2방향은 draw9patch에서 검은 선을 그려, 검은 선 길이의 교차점이 확장 가능한 범위입니다
그림에서3、4내용이 채울 수 있는 영역을 나타내는 방향의 검은 선 길이의 교차점

ShapeDrawable

색상을 통해 그래픽을 구성할 수 있습니다. 단색 그래픽이나 빛내림 효과가 있는 그래픽이 가능합니다. 구성할 수 있는 그래픽은 rectangle, oval, ring, line입니다

빛내림 효과가 있는 원 예제:

<?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>

注意:1、Android:angle 값은 반드시45의 배수 2、oval은 타원을 그리기 위해 사용되며,size의 너비와 높이가 같을 때 원으로 그립니다

圆环示例:

<?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>

注:
1、android:useLevel을 false로 설정하면 적절한 효과를 보이지 않습니다
2、innerRadius는 원형 링의 내 반지름이며,innerRadiusRatio는 내 반지름이 원형 링 너비의 비율로 내 반지름을 기준으로 합니다
3、thickness는 원형 링의 너비이며,thicknessRatio는 이 너비가 원형 링 너비의 비율로 원형 링 너비를 기준으로 합니다

常用属性

- android:shape 要绘制的形状,rectangle、oval、ring、line
- <stroke> 形状的描边,有以下属性
        - android:width 描边的宽度
        - android:color 描边的颜色
        - android:dashGap 绘制虚线的线宽
        - android:dashWidth 绘制虚线的线段间隔 (要绘制虚线,后两者均不能为0)
-<solid> 단색填充,android:color로 shape의 색상을 지정
- <gradient> 渐变效果,与solid을 함께 사용할 수 없으며 다음과 같은 속성이 있습니다
        - android:angle 渐变的角度,必须为45의 배수
        - android:startColor 渐变的起始颜色
        - android:centerColor 渐变的中间颜色
        - android:endColor 渐变的结束颜色
        - android:centerX 渐变的中心点横坐标
        - android:centerY 渐变的中心点纵坐标
        - android:gradientRadius 渐变半径
        - android:type 渐变类型,linear(线性)、sweep(扫视)、radial(径向)
- <corners> 表示矩形(rectangle)的四个角的角度,不适用于其他shape ,有如下属性
        - android:topLeftRadius、android:topRightRadius、android:bottomLeftRadius、android:bottomRightRadius 分别为设置左上角、右上角、左下角、右下角的角度
        - android:radius 为四角设置相同角度,优先级低,会被其他四个属性覆盖
- <size> shape的宽高,对应着android:width、android:height
        -  shape默认无宽高,getIntrinsicHeight、getIntrinsicWidth返回-1
        -  通过size可以设置其宽高,但作为view背景时任然会被拉伸或缩小为 view大小
- <padding> 设置容纳shape的view的空白间距

StateListDrawable

可以看作是一个状态选择器,通过view不同的状态选择对应的item中的drawable显示

예제:

<?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>

常见状态

android:state_pressed 当按住一个view时,按下的状态
android:state_checked 当一个view被选中时,适用于CheckBox
android:state_selected 当一个view被选择时
android:state_enabled 当一个view处于可用状态
android:state_focused 当一个view获取焦点

LayerDeawable

LayerDeawable

예제:

<?xml version="1.0" encoding="utf-8"?>
대표하는 것은 분할된 Drawable 집합으로, ps에서의 레이어 개념과 유사하며, 여러 개의 drawable을 다른 레이어에 배치하여 겹치는 효과를 만들 수 있습니다.-<level//schemas.android.com/apk/res/android">
 <item android:drawable="@mipmap/night" />
 photo0"
  android:drawable="@mipmap"/photo6"
  <layer />
</android:gravity="center"-level

layer

1주의사항:-layer
2list은 여러 개의 item을 포함할 수 있으며, 각 item은 drawable을 나타내며, 추가된 item은 이전에 추가된 item을 덮습니다.-layer
3list에 있는 모든 drawable이 view의 크기에 맞게 확대 축소됩니다. android:gravity를 통해 확대 축소 효과를 조절할 수 있습니다.

위치를 설정할 수 있으며, android:top, android:bottom, android:left, android:right

LevelListDrawable10대표하며, 각 Drawable에 등급(level)이 있어 LevelListDrawable가 다른 Drawable로 전환할 수 있습니다. 등급 범위는 0에서
예제:

<?xml version="1.0" encoding="utf-8"?>
000 사이에서, android:maxLevel을 최대 level로 설정하고, android:minLevel을 최소 level로 설정-<level//schemas.android.com/apk/res/android">
 photo0"
  android:drawable="@mipmap"/list xmlns:android="http:
  <item2android:minLevel="
  android:maxLevel="10" />
 photo0"
  android:drawable="@mipmap"/photo1"
  <item4android:minLevel="
  android:maxLevel="3android:minLevel=" />
</0"-level

list>

 //level을 설정하여 다른 Drawable을 전환할 수 있습니다. 코드에서1ImageView의 배경을 photo로 전환하려면 35 ImageView의 배경을 photo0으로 전환하려면3،40에서
 iv.setImageLevel(35); 
 //0~ 15ImageView의 배경을 photo0으로 전환하려면10~20에서
 iv.setImageLevel(15);

TransitionDrawable

LayerDeawable의 서브 클래스, 두 개의 Drawable의 진입 및 퇴장 효과를 구현하기 위해 사용
예제:

xml 파일 정의

<?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>

ImageView에 src 설정, Java 코드에서

 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

level에 따라Drawable을 특정 비율로 줄이면, level이 0이면 보이지 않으며,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

자신의 등급(level)에 따라 다른 Drawable을 자르는 데 사용하며, 자르는 방향은 android:clipOrientation, android:gravity로 결정됩니다. level을 설정하여 자르기, level의 크기는 0에서10000, level이 0이면 전혀 표시되지 않으며,10000이면 완전히 표시됩니다
xml 정의

<?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" />

level을 설정하여 잘라내기

 ImageView iv = (ImageView) findViewById(R.id.iv_clip);
 ClipDrawable drawable= (ClipDrawable) iv.getDrawable();
 drawable.setLevel(5000); // 설정된 level이 클수록 잘라내기 범위가 작아집니다

속성

android:clipOrientation, 수평 방향 잘라내기, 수직 방향 잘라내기
android:gravity, 잘라내기 방향과 함께 사용

자체형태의 Drawable

자체형태의 원형 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;
 }
}

자체형태의 둥근角을 가진 사각형 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();
 }
}

사용자 정의 Drawable의 일반 단계

 1사용자 정의 Drawable 클래스는 Drawable에서 상속
 2getOpacity, setColorFilter, setAlpha 등의 메서드를 구현
 3onDraw 메서드에서 그리기
 4사용자 정의 Drawable이 고정된 크기를 가지고 있다면 getIntrinsicWidth, getIntrinsicHeight 메서드를 구현해야 합니다.

이것이 이 문서의 모든 내용입니다. 많은 도움이 되길 바라며, 모두가呐喊 강의를 많이 지지해 주시길 바랍니다.

고지사항: 이 문서의 내용은 인터넷에서 가져왔으며, 저작권자가 모두 소유하고 있으며, 인터넷 사용자가 자발적으로 기여하고 자체로 업로드한 내용입니다. 이 사이트는 소유권을 가지지 않으며, 인공 편집을하지 않았으며, 관련 법적 책임을 부담하지 않습니다. 저작권 침해가 의심되는 내용이 발견되면, notice#w로 이메일을 보내 주시기 바랍니다.3codebox.com에 (보내는 이메일에서 #을 @으로 변경하십시오) 신고를 하시고 관련 증거를 제공하시면, 사이트는 즉시 저작권 침해 내용을 삭제할 것입니다.

좋아하는 것