我试图沿矩形绘制位图,但我不知道如何去做.有没有办法使用paint属性或其他东西沿Rect对象平铺位图?我看了,但是我找不到任何能让它做我需要的东西,大多数的平铺选项都不会为特定的实例平铺它们,它们会在整个屏幕上平铺它,所以使用该位图的一切都结束了在没有滚动或任何东西的情况下,同时沿着所有这些位图平铺一个大位图.
有任何想法吗?如果您需要更多信息让我知道,这是一个奇怪的问题所以我知道我可能没有提到重要的事情.
威廉
解决方法
有几种方法可以攻击它.我在这里概述其中两个……
单程:
您可以在位图周围定义BitmapDrawable.将其TileMode设置为重复.通过setBounds(rect)给它一些边界,其中rect是你的Rect实例.
以下是使用View onDraw作为上下文的简短示例:
- public class MyView extends View {
- Rect rect;
- Bitmap mBitmap;
- BitmapDrawable mDrawable;
- public MyView(Context context) {
- super(context);
- rect = new Rect(0,100,100);
- mBitmap = loadBitmap();
- mDrawable = new BitmapDrawable(context.getResources(),mBitmap);
- mDrawable.setTileModeXY(TileMode.REPEAT,TileMode.REPEAT);
- mDrawable.setBounds(rect);
- }
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- mDrawable.draw(canvas);
- }
- public Bitmap loadBitmap() {
- // included only for example sake
- Paint paint = new Paint();
- paint.setColor(Color.RED);
- Bitmap bm = Bitmap.createBitmap(10,10,Bitmap.Config.ARGB_8888);
- Canvas canvas = new Canvas(bm);
- canvas.drawRect(0,paint);
- paint.setStyle(Style.STROKE);
- paint.setColor(Color.BLUE);
- canvas.drawRect(0,9,paint);
- return bm;
- }
- }
注意:
您还可以在xml中定义BitmapDrawable,而不是在代码中执行.
另外,如果你知道你正在通过getResources()加载drawable .getDrawable(resourceId)确实只是一个Bitmap,你可以将它转换为BitmapDrawable并在那里设置TileMode.一个la:
- public class MyView extends View {
- Rect rect;
- BitmapDrawable mDrawable;
- public MyView(Context context) {
- super(context);
- rect = new Rect(0,400,240);
- mDrawable = (BitmapDrawable) context.getResources().getDrawable(R.drawable.ic_launcher);
- mDrawable.setTileModeXY(TileMode.REPEAT,TileMode.REPEAT);
- mDrawable.setBounds(rect);
- this.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.ic_launcher));
- }
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- mDrawable.draw(canvas);
- }
- }
此示例显示正在拉伸的背景,并在其上方绘制平铺版本.
其他方式:
在x和y方向循环并重复将位图绘制到rect中:
- public class MyView extends View {
- Rect rect;
- Bitmap mBitmap;
- public MyView(Context context) {
- super(context);
- rect = new Rect(0,100);
- mBitmap = loadBitmap();
- }
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- final int bmWidth = mBitmap.getWidth();
- final int bmHeight = mBitmap.getHeight();
- for (int y = 0,height = rect.height(); y < height; y += bmHeight) {
- for (int x = 0,width = rect.width(); x < width; x += bmWidth) {
- canvas.drawBitmap(mBitmap,x,y,null);
- }
- }
- }
- public Bitmap loadBitmap() {
- // included only for example sake
- Paint paint = new Paint();
- paint.setColor(Color.RED);
- Bitmap bm = Bitmap.createBitmap(10,paint);
- return bm;
- }
- }
我个人会去第一个(BitmapDrawable)方法.