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

android 自定义一个简单View总结

2017-03-02 19:14 609 查看
目前在练习自定义View;先从简单的练起。

需求:



公司的一个用户信息卡,上面有个人信息,有一个弧形背景,,还有用户描述等,这里只加上了用户头像;

之前的处理方法是通过一个背景图,然后使用背景图片+framlayout的布局进行处理。现在决定去通过自定义view的方式进行。

这边用的继承ImageView进行书写,实际情况可以完全不用继承这个,事实上继承这个View也确实用处不是很大;完全是可以继承

View来进行自定义,不过继承已存在的也是有好处的,可以处理wrap_content和padding的一些问题。

先说后面的这个背景:

通过Path进行背景的描画:

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mPath == null) {	//防止path初始化多次
mPath = new Path();
mWidth = getWidth();
mHeight = getHeight();
mIconRadius = mHeight / 9;//用户图片的半径
mPath.moveTo(0, 0);//起点(0,0)
mPath.lineTo(mWidth, 0);//
mPath.lineTo(mWidth, (float) (mHeight - (1 - Math.sqrt(3) / 2) * mWidth));//构图
for (int x = mWidth; x >= 0; x--) {
mPath.lineTo(x, (float) (Math.sqrt(Math.pow(mWidth, 2) - Math.pow(x - mWidth / 2, 2)) + mHeight - mWidth));
}
mPath.close();//构图
}
if (mBitmap != null && !flag) {
mBmWidth = mBitmap.getWidth();
mBmHeight = mBitmap.getHeight();
size = Math.min(mBmWidth, mBmHeight);//获得图片长度较小的一条边
Matrix matrix = new Matrix();
scale = (float) ((2 * mIconRadius * 1.0) / size);
matrix.postScale(scale, scale);//将图片最小一条边缩放到直径大小
//            mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBmWidth, mBmHeight, matrix, true);$$$$$
//            mBmWidth = mBitmap.getWidth();
//            mBmHeight = mBitmap.getHeight();
mBitmap = Bitmap.createBitmap(mBitmap, (mBmWidth - size) / 2, (mBmHeight - size) / 2, size, size);//取图片正中间的地方
BitmapShader shader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);//将图片放到Bitmapshader中
matrix.postTranslate((mWidth / 2 - mIconRadius),mIconRadius / 2);//将图片已到中间位置
shader.setLocalMatrix(matrix);//可以在这里设置,也可以在上面标记的地方说破
mBmPaint.setShader(shader);//将shader设置到paint中
flag = true;
//            canvas.setBitmap();
}
canvas.drawPath(mPath, mPaint);
canvas.drawCircle(mWidth / 2, mIconRadius * 3 / 2, mIconRadius, mBmPaint);
//        canvas.drawBitmap(mBitmap,0,0,null);
//        Canvas mCan = new Canvas(mBitmap);
}


这里说一下,如果matrix.postTranslate()不执行,那么图片默认是在(0,0)的位置,在要放置头像的地方就无法获得想要的部分;具体获得的是什么样子的和

BitmapShader shader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
中的TILEMODE有关

TileMode.CLAMP:如果目标区域大于图片大小;多出来的地方将被边缘颜色填充

TileMode.MIRROR:让图片镜像复制

TileMode.REPEAT:沿XY轴进行复制

所以如果不translate那么获得的头像具体样子和本身的MODE有关
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: