自定义Drawable
package com.loaderman.customviewdemo; import android.graphics.*; import android.graphics.drawable.Drawable; public class CustomDrawable extends Drawable { private Paint mPaint; private Bitmap mBitmap; private BitmapShader bitmapShader; private RectF mBound; public CustomDrawable(Bitmap bitmap) { mBitmap = bitmap; mPaint = new Paint(); mPaint.setAntiAlias(true); } @Override public void draw(Canvas canvas) { canvas.drawRoundRect(mBound, 20, 20, mPaint); } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { mPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT;//显示模式 } @Override public void setBounds(int left, int top, int right, int bottom) { super.setBounds(left, top, right, bottom); bitmapShader = new BitmapShader(Bitmap.createScaledBitmap(mBitmap, right - left, bottom - top, true), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mPaint.setShader(bitmapShader); mBound = new RectF(left, top, right, bottom); } // @Override // public int getIntrinsicWidth() { // return mBitmap.getWidth(); // } // // @Override // public int getIntrinsicHeight() { // return mBitmap.getHeight(); // } }
package com.loaderman.customviewdemo; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avator); CustomDrawable drawable = new CustomDrawable(bitmap); TextView tv = (TextView) findViewById(R.id.tv); tv.setBackgroundDrawable(drawable); } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!