bitemap 和UI画图工具

本文详细介绍了Android平台下的资源管理类Resources及图形处理类如Bitmap、Canvas等,并深入探讨了Drawable的各种子类及其应用场景。

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

 

  android.content.res资源类
  android.graphics底层图形类
  android.view显示类
  android.widget控件类

  一、android.content.res.Resources

  对于Android平台的资源类android.content.res.Resources可能很多网友比较陌生,一起来看看SDK上是怎么介绍的吧,Contains classes foraccessing application resources, such as raw asset files, colors, drawables,media or other other files in the package, plus important device configurationdetails (orientation, input types, etc.) that affect how the application maybehave.平时用到的二进制源文件raw、颜色colors、图形drawables和多媒体文件media的相关资源均通过该类来管理。
  intgetColor(int id) 对应res/values/colors.xml
  DrawablegetDrawable(int id) 对应res/drawable/
  XmlResourceParser getLayout(intid) 对应res/layout/
  StringgetString(int id) 和CharSequence getText(int id) 对应res/values/strings.xml
  InputStream openRawResource(intid) 对应res/raw/
  void parseBundleExtra (StringtagName, AttributeSet attrs, Bundle outBundle) 对应res/xml/
  String[]getStringArray(int id) res/values/arrays.xml
  float getDimension(int id) res/values/dimens.xml

  二、android.graphics.Bitmap

  作为位图操作类,Bitmap提供了很多实用的方法,常用的我们总结如下:
  booleancompress(Bitmap.CompressFormat format, int quality, OutputStream stream) 压缩一个Bitmap对象根据相关的编码、画质保存到一个OutputStream中。其中第一个压缩格式目前有JPG和PNG
  voidcopyPixelsFromBuffer(Buffer src) 从一个Buffer缓冲区复制位图像素
  voidcopyPixelsToBuffer(Buffer dst) 将当前位图像素内容复制到一个Buffer缓冲区
  我们看到创建位图对象createBitmap包含了6种方法在目前的Android 2.1 SDK中,当然他们使用的是API Level均为1,所以说从Android1.0 SDK开始就支持了,所以大家可以放心使用。
  staticBitmap createBitmap(Bitmap src)
  staticBitmap createBitmap(int[] colors, int width, int height, Bitmap.Config config)
  staticBitmap createBitmap(int[] colors, int offset, int stride, int width, intheight, Bitmap.Config config)
  staticBitmap createBitmap(Bitmap source, int x, int y, int width, int height, Matrixm, boolean filter)
  staticBitmap createBitmap(int width, int height, Bitmap.Config config)
  staticBitmap createBitmap(Bitmap source, int x, int y, int width, int height)
  staticBitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, booleanfilter) //创建一个可以缩放的位图对象
  final int getHeight() 获取高度
final int getWidth() 获取宽度
  finalboolean hasAlpha() 是否有透明通道
  voidsetPixel(int x, int y, int color) 设置某像素的颜色
  intgetPixel(int x, int y) 获取某像素的颜色,android开发网提示这里返回的int型是color的定义

  三、android.graphics.BitmapFactory

  作为Bitmap对象的I/O类,BitmapFactory类提供了丰富的构造Bitmap对象的方法,比如从一个字节数组、文件系统、资源ID、以及输入流中来创建一个Bitmap对象,下面本类的全部成员,除了decodeFileDescriptor外其他的重载方法都很常用。
  staticBitmap decodeByteArray(byte[] data, int offset, int length) //从字节数组创建
  staticBitmap decodeByteArray(byte[] data, int offset, int length,BitmapFactory.Options opts)
  static Bitmap decodeFile(StringpathName, BitmapFactory.Options opts) //从文件创建,路径要写全
  staticBitmap decodeFile(String pathName)
  staticBitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding,BitmapFactory.Options opts) //从输入流句柄创建
  staticBitmap decodeFileDescriptor(FileDescriptor fd)
  static BitmapdecodeResource(Resources res, int id) //AndroidAPK文件资源中创建,android123提示是从/res/drawable
  staticBitmap decodeResource(Resources res, int id, BitmapFactory.Options opts)
  staticBitmap decodeResourceStream(Resources res, TypedValue value, InputStream is,Rect pad, BitmapFactory.Options opts)
  static BitmapdecodeStream(InputStream is) //从一个输入流中创建
  staticBitmap decodeStream(InputStream is, Rect outPadding, BitmapFactory.Optionsopts)

  四、android.graphics.Canvas

  从J2ME MIDLET时我们就知道Java提供了Canvas类,而目前在Android平台中,它主要任务为管理绘制过程,The Canvas class holds the "draw" calls. To drawsomething, you need 4 basic components: A Bitmap to hold the pixels, a Canvasto host the draw calls (writing into the bitmap), a drawing primitive (e.g.Rect, Path, text, Bitmap), and a paint (to describe the colors and styles forthe drawing).
  该类主要提供了三种构造方法,分别为构造一个空的Canvas、从Bitmap中构造和从GL对象中创建,如下
  Canvas()
  Canvas(Bitmapbitmap)
  Canvas(GLgl)
  同时Canvas类的一些字段保存着重要的绘制方法定义,比如Canvas.HAS_ALPHA_LAYER_SAVE_FLAG保存时需要alpha层,对于Canvas类提供的方法很多,每个都很重要,下面我们一一作介绍
  booleanclipPath(Path path)
  booleanclipPath(Path path, Region.Op op)
  booleanclipRect(float left, float top, float right, float bottom)
  booleanclipRect(Rect rect)
  booleanclipRect(float left, float top, float right, float bottom, Region.Op op)
  booleanclipRect(Rect rect, Region.Op op)
  booleanclipRect(RectF rect)
  booleanclipRect(RectF rect, Region.Op op)
  booleanclipRect(int left, int top, int right, int bottom)
  booleanclipRegion(Region region, Region.Op op)
  booleanclipRegion(Region region)
  voidconcat(Matrix matrix)
  voiddrawARGB(int a, int r, int g, int b)
  voiddrawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter,Paint paint)
  voiddrawBitmap(Bitmap bitmap, Matrix matrix, Paint paint)
  voiddrawBitmap(int[] colors, int offset, int stride, float x, float y, int width,int height, boolean hasAlpha, Paint paint)
  voiddrawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint)
  voiddrawBitmap(Bitmap bitmap, float left, float top, Paint paint)
  voiddrawBitmap(int[] colors, int offset, int stride, int x, int y, int width, intheight, boolean hasAlpha, Paint paint)
  voiddrawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint)
  voiddrawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight, float[] verts, intvertOffset, int[] colors, int colorOffset, Paint paint)
  voiddrawCircle(float cx, float cy, float radius, Paint paint)
  voiddrawColor(int color)
  voiddrawColor(int color, PorterDuff.Mode mode)
  voiddrawLine(float startX, float startY, float stopX, float stopY, Paint paint)
  voiddrawLines(float[] pts, Paint paint)
  voiddrawLines(float[] pts, int offset, int count, Paint paint)
  voiddrawOval(RectF oval, Paint paint)
  voiddrawPaint(Paint paint)
  voiddrawPath(Path path, Paint paint)
  voiddrawPicture(Picture picture, RectF dst)
  voiddrawPicture(Picture picture, Rect dst)
  voiddrawPicture(Picture picture)
  voiddrawPoint(float x, float y, Paint paint)
  voiddrawPoints(float[] pts, int offset, int count, Paint paint)
  voiddrawPoints(float[] pts, Paint paint)
  voiddrawPosText(char[] text, int index, int count, float[] pos, Paint paint)
  voiddrawPosText(String text, float[] pos, Paint paint)
  voiddrawRGB(int r, int g, int b)
  voiddrawRect(RectF rect, Paint paint)
  voiddrawRect(float left, float top, float right, float bottom, Paint paint)
  voiddrawRect(Rect r, Paint paint)
  voiddrawRoundRect(RectF rect, float rx, float ry, Paint paint)
  voiddrawText(String text, int start, int end, float x, float y, Paint paint)
  voiddrawText(char[] text, int index, int count, float x, float y, Paint paint)
  voiddrawText(String text, float x, float y, Paint paint)
  voiddrawText(CharSequence text, int start, int end, float x, float y, Paint paint)
  voiddrawTextOnPath(String text, Path path, float hOffset, float vOffset, Paintpaint)
  void drawTextOnPath(char[]text, int index, int count, Path path, float hOffset, float vOffset, Paintpaint)
  voiddrawVertices(Canvas.VertexMode mode, int vertexCount, float[] verts, intvertOffset, float[] texs, int texOffset, int[] colors, int colorOffset, short[]indices, int indexOffset, int indexCount, Paint paint)
  static voidfreeGlCaches()
  booleangetClipBounds(Rect bounds)
  final RectgetClipBounds()
  intgetDensity()
  DrawFiltergetDrawFilter()
  GL getGL()
  intgetHeight()
  voidgetMatrix(Matrix ctm)
  final MatrixgetMatrix()
  intgetSaveCount()
  intgetWidth()
  booleanisOpaque()
  booleanquickReject(Path path, Canvas.EdgeType type)
  booleanquickReject(float left, float top, float right, float bottom, Canvas.EdgeTypetype)
  booleanquickReject(RectF rect, Canvas.EdgeType type)
  voidrestore()
  voidrestoreToCount(int saveCount)
  final voidrotate(float degrees, float px, float py)
  voidrotate(float degrees)
  int save()
  int save(intsaveFlags)
  int saveLayer(float left,float top, float right, float bottom, Paint paint, int saveFlags)
  intsaveLayer(RectF bounds, Paint paint, int saveFlags)
  intsaveLayerAlpha(float left, float top, float right, float bottom, int alpha, intsaveFlags)
  intsaveLayerAlpha(RectF bounds, int alpha, int saveFlags)
  final voidscale(float sx, float sy, float px, float py)
  voidscale(float sx, float sy)
  voidsetBitmap(Bitmap bitmap)
  voidsetDensity(int density)
  voidsetDrawFilter(DrawFilter filter)
  voidsetMatrix(Matrix matrix)
  void setViewport(intwidth, int height)
  voidskew(float sx, float sy)
  voidtranslate(float dx, float dy)

  五、android.graphics.Color

  有关Android平台上表示颜色的方法有很多种,Color提供了常规主要颜色的定义比如Color.BLACK和Color.GREEN等等,我们平时创建时主要使用以下静态方法
  static int argb(int alpha, intred, int green, int blue) 构造一个包含透明对象的颜色
static int rgb(intred, int green, int blue) 构造一个标准的颜色对象
  static intparseColor(String colorString) 解析一种颜色字符串的值,比如传入Color.BLACK
  本类返回的均为一个整形类似 绿色为0xff00ff00,红色为0xffff0000。我们将这个DWORD型看做AARRGGBB,AA代表Aphla透明色,后面的就不难理解,每个分成WORD整好为0-255。


今天我们继续介绍Android平台底层绘图类的相关内容,在Android UI开发专题(一) 之界面设计中我们介绍了有关Android平台资源使用以及Bitmap相关类的操作,接下来将会以实例的方式给大家演示各种类的用处以及注意点。今天我们继续了解android.graphics包中比较重要的绘图类。
  一、 android.graphics.Matrix

  有关图形的变换、缩放等相关操作常用的方法有:
  void reset()// 重置一个matrix对象。
  voidset(Matrix src) //复制一个源矩阵,和本类的构造方法 Matrix(Matrix src) 一样
  booleanisIdentity() //返回这个矩阵是否定义(已经有意义)
  voidsetRotate(float degrees) //指定一个角度以0,0为坐标进行旋转
  voidsetRotate(float degrees, float px, float py) //指定一个角度以px,py为坐标进行旋转
  voidsetScale(float sx, float sy) // 缩放
  voidsetScale(float sx, float sy, float px, float py) //以坐标px,py进行缩放
  voidsetTranslate(float dx, float dy) //平移
  void setSkew(float kx, float ky, float px, float py) //以坐标px,py进行倾斜
  void setSkew(float kx, float ky) //倾斜

  二、android.graphics.NinePatch

  NinePatch是Android平台特有的一种非矢量图形自然拉伸处理方法,可以帮助常规的图形在拉伸时不会缩放,实例中Android开发网提示大家对于Toast的显示就是该原理,同时SDK中提供了一个工具名为Draw 9-Patch,有关该工具的使用方法可以参考我们经发布的 Draw 9-Patch使用方法介绍一文。由于该类提供了高质量支持透明的缩放方式,所以图形格式为PNG,文件命名方式为.9.png 的后缀比如android123.9.png。

  三、android.graphics.Paint

  Paint类我们可以理解为画笔、画刷的属性定义,本类常用的方法如下:
  void reset()//重置
  voidsetARGB(int a, int r, int g, int b) 或 void setColor(int color) 均为设置Paint对象的颜色
  voidsetAntiAlias(boolean aa) //是否抗锯齿,需要配合void setFlags (Paint.ANTI_ALIAS_FLAG) 来帮助消除锯齿使其边缘更平滑。
  ShadersetShader(Shader shader) //设置阴影,Shader类是一个矩阵对象,如果为NULL将清除阴影。
  voidsetStyle(Paint.Style style) //设置样式,一般为 FILL 填充,或者STROKE凹陷效果。
  voidsetTextSize(float textSize) //设置字体大小
  voidsetTextAlign(Paint.Align align) //文本对齐方式
  TypefacesetTypeface(Typeface typeface) //设置字体,通过Typeface可以加载Android内部的字体,一般为宋体对于中文,部分ROM可以自己添加比如雅黑等等
  voidsetUnderlineText(boolean underlineText) //是否设置下划线,需要撇和void setFlags (Paint.UNDERLINE_TEXT_FLAG) 方法。

  四、android.graphics.Rect

  Rect我们可以理解为矩形区域,类似的还有Point一个点,Rect类除了表示一个矩形区域位置描述外,android123提示主要可以帮助我们计算图形之间是否碰撞(包含)关系,对于Android游戏开发比较有用,其主要的成员contains包含了三种重载方法,来判断包含关系
  booleancontains(int left, int top, int right, int bottom)
  booleancontains(int x, int y)
  booleancontains(Rect r)

  五、android.graphics.Region

  Region在Android平台中表示一个区域和Rect不同的是,它表示的是一个不规则的样子,可以是椭圆、多边形等等,而Rect仅仅是矩形。同样Region的boolean contains(int x, int y) 成员可以判断一个点是否在该区域内

  六、android.graphics.Typeface

  Typeface类是帮助描述一个字体对象,在TextView中通过使用setTypeface方法来制定一个输出文本的字体,其直接构造调用成员create方法可以直接指定一个字体名称和样式,比如
  staticTypeface create(Typeface family, int style)
  staticTypeface create(String familyName, int style)
  同时使用isBold和isItalic方法可以判断出是否包含粗体或斜体的字型。
  finalboolean isBold()
  finalboolean isItalic()
  该类的创建方法还有从apk的资源或从一个具体的文件路径,其具体方法为
  static TypefacecreateFromAsset(AssetManager mgr, String path)
  staticTypeface createFromFile(File path)
  staticTypeface createFromFile(String path)
  有关Android平台的图形、图像我们在前两节中已经整理出来,下次我们将首先讲述下NinePatch的实例应用。

 

1.      本次我们主要讲解Android平台下的各种Drawable,这里在SDK的android.graphics.drawable包下面可以看到有各种Drawable类多达十几种,它们到底之间有什么关系和区别呢?

  一、AnimationDrawable

  顾名思义该类主要表示动画的图形类,可以实现逐帧播放的效果,下面代码示例如下
  1. 定义一个cwj_animation.xml 放到res/drawable 目录下,其中定义的属性duration为延时,单位为毫秒,而oneshot属性表示是否仅播放一次,内容为:
1<animation-list android:id="selected"android:oneshot="false">
2<item android:drawable="@drawable/cwj0"android:duration="30"
/>
3<item android:drawable="@drawable/cwj1"android:duration="30"
/>
4<item android:drawable="@drawable/cwj2" android:duration="30"
/>
5<item android:drawable="@drawable/cwj3"android:duration="30"
/>
6<item android:drawable="@drawable/cwj4"android:duration="30"
/>
7<item android:drawable="@drawable/cwj5"android:duration="30"
/>
8</animation-list>
9
10

       2.在java中调用也很简单
  ImageViewimg = (ImageView)findViewById(R.id.cwj_image); //首先声明一个ImageView对象在xml布局文件中
  img.setBackgroundResource(R.drawable.cwj_animation);//我们刚才的animation定义的xml文件
  AnimationDrawableframeAnimation = (AnimationDrawable) img.getBackground(); //构造AnimationDrawable对象
  frameAnimation.start()//开始播放动画
  3.AnimationDrawable类还提供了一些常用的方法如下:
  void stop() 停止
  voidaddFrame(Drawable frame, int duration) 添加一帧,类似xml中的布局
  DrawablegetFrame(int index) 返回某帧的Drawable图形
  intgetNumberOfFrames() 返回总共动画帧数
  booleanisOneShot() 是否仅播放一次
  booleanisRunning() 是否正在播放

  二、BitmapDrawable

  Android平台中对于缩放、变形的Bitmap对象由BitmapDrawable类表示,其构造方法也很简单,由于该类继承于android.graphics.drawable.Drawable,相对Drawable而言提供了更多的有关位图的操作方法,主要的构造方法如下:
  BitmapDrawable()//直接构造一个空的对象,这样方式不推荐使用,SDK标记为deprecated.未来可能无法使用。
  BitmapDrawable(Resources res) //从资源中构造
  BitmapDrawable(Bitmapbitmap) //从Bitmap对象直接构造,但也是不推荐,而是希望用下一种
  BitmapDrawable(Resourcesres, Bitmap bitmap) //从bitmap中创建设置初始的分辨率从res中
  BitmapDrawable(Stringfilepath) //从具体文件路径构造,也不推荐使用,而是下一种更好
  BitmapDrawable(Resourcesres, String filepath) //同上
  BitmapDrawable(InputStreamis) //从输入流中构造,同样推荐下面的方法
  BitmapDrawable(Resourcesres, InputStream is) //同上
  在BitmapDrawable类中相对于Drawable类主要新增了以下几种方法,均比较实用:
  final BitmapgetBitmap() 获取一个Bitmap对象
  intgetOpacity() //获取透明度
  voidsetAntiAlias(boolean aa) //是否抗锯齿
  voidsetTargetDensity(Canvas canvas) //设置目标Canvas密度
  voidsetTargetDensity(DisplayMetrics metrics)
实例: //功能:显示缩略图,大小为40*40

2.     

3.              //通过openRawResource获取一个inputStream对象  

4.              InputStream inputStream = getResources().openRawResource(R.drawable.test);  

5.              //通过一个InputStream创建一个BitmapDrawable对象  

6.              BitmapDrawable drawable = new BitmapDrawable(inputStream);  

7.              //通过BitmapDrawable对象获得Bitmap对象  

8.              Bitmap bitmap = drawable.getBitmap();  

9.             //利用Bitmap对象创建缩略图  

10.           bitmap = ThumbnailUtils.extractThumbnail(bitmap, 4040);  

11.            //imageView 显示缩略图的ImageView  

12.            imageView.setImageBitmap(bitmap);

 

 

 

 

 

1.       //功能:image2从image1中截取120*120大小后显示,截取起始坐标为(x,y)

2.       

3.     BitmapDrawable bitmapDrawable = (BitmapDrawable)image1.getDrawable();

4.      //获取第一个图片显示框中的位图

5.      Bitmap  bitmap =bitmapDrawable.getBitmap();

6.      //显示图片的指定区域

7.     image2.setImageBitmap(Bitmap.createBitmap(bitmap, x,y, 120, 120));

8.      image2.setAlpha(alpha);


  三、ClipDrawable

  ColorDrawable
  Drawable
  GradientDrawable
  InsetDrawable
  LayerDrawable
  LevelListDrawable
  NinePatchDrawable
  PaintDrawable
  PictureDrawable
  RotateDrawable
  ScaleDrawable
  ShapeDrawable
  StateListDrawable
  TransitionDrawable
  以上的类型在常见的开发一般较少出现,主要是基类构造使用,Android内部的多个Widget基础控件使用了,感兴趣的网友可以查看开源GIT中的相关内容。

 

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值