android基础之drawable

本文详细介绍了在Android应用中加载和使用图像、动画的方法,包括从assets文件夹加载图片,从drawable资源中获取drawable,以及如何将图片转换为drawable。此外,文章还覆盖了XMLDrawable、SharpDrawable、StateDrawable、TransitionDrawable、VectorDrawable和AnimationDrawable等高级用法,同时介绍了如何在按钮点击事件中实现动画过渡效果。最后,文章提到了自定义drawable如9Patchdrawable的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、加载bitmap 和 drawable

  • 从asserts文件夹创建bitmap,并赋给imageview
    AssetManager manager = getAssets();

    // read a Bitmap from Assets 
    InputStream open = null;
    try { 
      open = manager.open("logo.png");
      Bitmap bitmap = BitmapFactory.decodeStream(open);
      // Assign the bitmap to an ImageView in this layout 
      ImageView view = (ImageView) findViewById(R.id.imageView1);
      view.setImageBitmap(bitmap);
    } catch (IOException e) {
      e.printStackTrace();
    } finally { 
      if (open != null) {
        try { 
          open.close();
        } catch (IOException e) {
          e.printStackTrace();
        } 
      } 
    }  
  • 从res/drawable 中获取drawable
    Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_search);
  • 基于新的宽高尺寸获取bitmap
Bitmap originalBitmap =<initial setup> ; 
Bitmap resizedBitmap = 
        Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false); 
  • 将bitmap转换为drawable
//Convert Bitmap to Drawable
Drawable d = new BitmapDrawable(getResources(),bitmap);

二、XML Drawable

  • Sharp Drawable
<?xml version="1.0" encoding="UTF-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <stroke
    android:width="2dp"
    android:color="#FFFFFFFF" />
  <gradient
    android:endColor="#DDBBBBBB"
    android:startColor="#DD777777"
    android:angle="90" />
  <corners
    android:bottomRightRadius="7dp"
    android:bottomLeftRadius="7dp"
    android:topLeftRadius="7dp"
    android:topRightRadius="7dp" />
</shape> 
  • State Drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/button_pressed"
    android:state_pressed="true" />
  <item android:drawable="@drawable/button_checked"
    android:state_checked="true" />
  <item android:drawable="@drawable/button_default" />
</selector> 
  • transition Drawable
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/first_image" />
  <item android:drawable="@drawable/second_image" />
</transition> 
final ImageView image = (ImageView) findViewById(R.id.image);
final ToggleButton button = (ToggleButton) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() { 
  @Override 
  public void onClick(final View v) {
    TransitionDrawable drawable = (TransitionDrawable) image.getDrawable();
    if (button.isChecked()) {
      drawable.startTransition(500);
    } else { 
      drawable.reverseTransition(500);
    } 
  } 
});  
  • Vector drawable
    Android 5.0 开始可以定义Vector drawable ,优点是可以自动按比例缩放到设备的像素密度
<vector xmlns:android="http://schemas.android.com/apk/res/android"
     android:height="64dp"
     android:width="64dp"
     android:viewportHeight="600"
     android:viewportWidth="600" >
     <group
         android:name="rotationGroup"
         android:pivotX="300.0"
         android:pivotY="300.0"
         android:rotation="45.0" >
         <path
             android:name="v"
             android:fillColor="#000000"
             android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />
     </group>
 </vector> 
  • Animation Drawable
    可以通过 setBackgroundResource()的方式给view设置animation drawable
<!-- Animation frames are phase*.png files inside the
 res/drawable/ folder -->
 <animation-list android:id="@+id/selected" android:oneshot="false">
    <item android:drawable="@drawable/phase1" android:duration="400" />
    <item android:drawable="@drawable/phase2" android:duration="400" />
    <item android:drawable="@drawable/phase3" android:duration="400" />
 </animation-list> 
ImageView img = (ImageView)findViewById(R.id.yourid);
img.setBackgroundResource(R.drawable.your_animation_file);

 // Get the AnimationDrawable object. 
 AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

 // Start the animation (looped playback by default). 
 frameAnimation.start();
  • 9 Patch drawable

  • 自定义 drawable
    创建custom Drawable类

package com.vogella.android.drawables.custom; 

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;

public class MyRoundCornerDrawable extends Drawable {

  private Paint paint;

  public MyRoundCornerDrawable(Bitmap bitmap) {
    BitmapShader shader;
    shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
        Shader.TileMode.CLAMP);
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(shader);
  } 

  @Override 
  public void draw(Canvas canvas) {
    int height = getBounds().height();
    int width = getBounds().width();
    RectF rect = new RectF(0.0f, 0.0f, width, height);
    canvas.drawRoundRect(rect, 30, 30, paint);
  } 

  @Override 
  public void setAlpha(int alpha) {
    paint.setAlpha(alpha);
  } 

  @Override 
  public void setColorFilter(ColorFilter cf) {
    paint.setColorFilter(cf);
  } 

  @Override 
  public int getOpacity() { 
    return PixelFormat.TRANSLUCENT;
  } 

}  

在布局文件中使用

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:contentDescription="TODO" />

</RelativeLayout> 
package com.vogella.android.drawables.custom; 

import java.io.InputStream;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {

  @Override 
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView button = (ImageView) findViewById(R.id.image);
    InputStream resource = getResources().openRawResource(R.drawable.dog);
    Bitmap bitmap = BitmapFactory.decodeStream(resource);
    button.setBackground(new MyRoundCornerDrawable(bitmap));
  } 

}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值