项目开发中需要开发漂亮的界面,其中一些界面需要花边
例如:
如果切图切整一条,那么他只适用于该分辨率的手机,如果放到其它手机上或放到平板上,他就会被拉长,用.9图也是一样会被拉长,那么该怎么办呢?
对于这种情况,我们只好切出波浪线重复的那一部分:
img_wave.png
拿到这部分之后,我们开始自定义一个view,用view的ondraw绘制横向绘制这个重复部分、
绘制之前,我们需要将img_wave放大到view得高度:
float scale = getMeasuredHeight()*1f/bitmap.getHeight(); float width = bitmap.getWidth()*1f*scale;
同时也需要计算绘制的个数,让绘制的效果达到最好:
waveCount = (int)(getMeasuredWidth()*1f/bitmap.getWidth())+1;
上面+1的原因是因为让它多出一个,足以铺满,
+1个之后宽度超出view宽度,再重新计算img_wavw的绘制宽度及缩放比例:
waveWidth = width - ((width*waveCount-getMeasuredWidth())/waveCount); waveScale = waveWidth*1f/bitmap.getWidth();最后,横向绘制波浪:
matrix.setScale(waveScale, waveScale); for (int i = 0; i < waveCount; i++) { canvas.drawBitmap(bitmap_wave.get(), matrix, paint); matrix.postTranslate(waveWidth, 0); }
是不是很棒?最后贴出代码,希望能帮到大家:
/** * 无缝花边 * @author touch_ping * */ public class WaveLineView extends View { private final static int waveRes = R.drawable.img_wave; private static SoftReference<Bitmap> bitmap_wave;// 背景 private Context mcontext; private static Paint paint; private static Matrix matrix; private static float waveWidth; private static float waveScale; private static int waveCount; public WaveLineView(Context context) { super(context); init(context); } public WaveLineView(Context context, AttributeSet attrs) { super(context, attrs, 0); init(context); } private void init (Context context) { mcontext = context; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (paint==null) { paint = new Paint(); } if (matrix==null) { matrix = new Matrix(); } if (bitmap_wave==null || bitmap_wave.get()==null) { // 从资源文件中生成位图 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), waveRes); float scale = getMeasuredHeight()*1f/bitmap.getHeight(); float width = bitmap.getWidth()*1f*scale; waveCount = (int)(getMeasuredWidth()*1f/width)+1; waveWidth = width - ((width*waveCount-getMeasuredWidth())/waveCount); waveScale = waveWidth*1f/bitmap.getWidth(); bitmap_wave = new SoftReference<Bitmap>(bitmap); } matrix.setScale(waveScale, waveScale); for (int i = 0; i < waveCount; i++) { canvas.drawBitmap(bitmap_wave.get(), matrix, paint); matrix.postTranslate(waveWidth, 0); } } }
原文地址:http://blog.csdn.net/u010499721/article/details/44683587