android – 如何在我的自定义视图的画布中设置位图图像?

前端之家收集整理的这篇文章主要介绍了android – 如何在我的自定义视图的画布中设置位图图像?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的主类中有一个Bitmap对象.我需要将此位图发送到我的自定义视图类,以将其设置为在画布上进一步处理的背景.

例如,有一个名为setPicture的方法,它接收位图作为参数.那么,如何在画布上绘制这个位图呢?

请参阅以下代码

  1. public class TouchView extends View {
  2.  
  3. final int MIN_WIDTH = 75;
  4. final int MIN_HEIGHT = 75;
  5. final int DEFAULT_COLOR = Color.RED;
  6. int _color;
  7. final int STROKE_WIDTH = 2;
  8.  
  9. private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  10. private float x,y;
  11. private boolean touching = false;
  12.  
  13. public TouchView(Context context,AttributeSet attrs,int defStyle) {
  14. super(context,attrs,defStyle);
  15. // TODO Auto-generated constructor stub
  16. init();
  17. }
  18.  
  19. public TouchView(Context context,AttributeSet attrs) {
  20. super(context,attrs);
  21. // TODO Auto-generated constructor stub
  22. init();
  23. }
  24.  
  25. public TouchView(Context context) {
  26. super(context);
  27. // TODO Auto-generated constructor stub
  28. init();
  29. }
  30.  
  31. private void init() {
  32. setMinimumWidth(MIN_WIDTH);
  33. setMinimumHeight(MIN_HEIGHT);
  34. _color = DEFAULT_COLOR;
  35. }
  36.  
  37. @Override
  38. protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
  39. // TODO Auto-generated method stub
  40. setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),MeasureSpec.getSize(heightMeasureSpec));
  41. }
  42.  
  43. @Override
  44. protected void onDraw(Canvas canvas) {
  45. // TODO Auto-generated method stub
  46. super.onDraw(canvas);
  47.  
  48. if (touching) {
  49. paint.setStrokeWidth(STROKE_WIDTH);
  50. paint.setColor(_color);
  51. paint.setStyle(Paint.Style.FILL);
  52. canvas.drawCircle(x,y,75f,paint);
  53. }
  54. }
  55.  
  56. public void setPicture (Bitmap bitmap) {
  57.  
  58. ///////
  59. This method must receive my bitmap to draw it on canvas!!!!!!!!!!!!!!!
  60. ///////
  61.  
  62.  
  63. }
  64.  
  65. public void setColor(int color) {
  66. _color = color;
  67. }
  68.  
  69. @Override
  70. public boolean onTouchEvent(MotionEvent motionEvent) {
  71. // TODO Auto-generated method stub
  72.  
  73. switch (motionEvent.getAction()) {
  74. case MotionEvent.ACTION_MOVE:
  75. case MotionEvent.ACTION_DOWN:
  76. x = motionEvent.getX();
  77. y = motionEvent.getY();
  78. touching = true;
  79. break;
  80. default:
  81. touching = false;
  82. }
  83. invalidate();
  84. return true;
  85. }

}

我应该如何将此位图发送到onDraw?

解决方法

在你的onDraw()方法里面,

做就是了

  1. canvas.drawBitmap(myBitmap,null);

myBitmap是你的位图变量.

0,0指的是绘制的坐标,即左上角.

还有其他的Apis,可以吸引到某些地区等.

More info can be found here in the api docs.

或者:改为扩展ImageView,并使用setImageBitmap(Bitmap src);实现这一目标的方法.

猜你在找的Android相关文章