您的位置:首页 > 移动开发 > Android开发

Android Canvas和Paint用法

2017-04-08 17:58 274 查看
一个简单的Demo,自定义一个View,继承自ImageView。

public class MyImageView extends ImageView {
protected Context mContext;

public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Resources resources = this.getContext().getResources();
Drawable drawable = resources.getDrawable(R.drawable.img4);
Bitmap bitmap =Bitmap.createBitmap(100,100,Bitmap.Config.ARGB_8888);
Canvas canvas1 = new Canvas(bitmap);
drawable.setBounds(0,0,100,100);;
drawable.draw(canvas1);
canvas.drawBitmap(bitmap,0,0,mPaint);

}
}
R.drawable.img4替换成自己的图片。

布局文件中加入

<com.example.luzhao.ceshi7.view.MyImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

颜色部分需要改成自己类名。

最重要的是宽度和高度是需要为一定的大小,如果设置为wrap_content,很可能就看不到想要的图像了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息