android canvas 显示图片
时间: 2023-07-28 08:38:02 浏览: 48
要在Android中使用Canvas显示图片,可以按照以下步骤:
1. 在布局文件中添加一个自定义View,例如:
```xml
<com.example.MyCanvasView
android:id="@+id/my_canvas_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 创建一个自定义View,继承自View或其子类,例如:
```java
public class MyCanvasView extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mPaint;
public MyCanvasView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(5);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, 0, 0, null);
}
public void drawImage(Bitmap bitmap, float x, float y) {
mCanvas.drawBitmap(bitmap, x, y, mPaint);
invalidate();
}
}
```
3. 在Activity中获取该自定义View,并调用其drawImage()方法,例如:
```java
MyCanvasView myCanvasView = findViewById(R.id.my_canvas_view);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
myCanvasView.drawImage(bitmap, 100, 100);
```
这样就能在自定义View中使用Canvas显示图片了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)