libgdx学习记录24——九宫格NinePatch

NinePatch用于图片纹理拉伸显示。当图片拉伸时,4个角不会拉伸,而只有中间的部分会拉伸,适合做圆角矩形类的Button。

简单示例:

 1 package com.fxb.newtest;
 2 
 3 import com.badlogic.gdx.ApplicationAdapter;
 4 import com.badlogic.gdx.Gdx;
 5 import com.badlogic.gdx.Input;
 6 import com.badlogic.gdx.InputAdapter;
 7 import com.badlogic.gdx.graphics.GL10;
 8 import com.badlogic.gdx.graphics.Texture;
 9 import com.badlogic.gdx.graphics.g2d.NinePatch;
10 import com.badlogic.gdx.graphics.g2d.SpriteBatch;
11 import com.badlogic.gdx.graphics.g2d.TextureRegion;
12 
13 public class Lib029_NinePatch extends ApplicationAdapter{
14 
15     NinePatch patch;
16     SpriteBatch batch;
17     TextureRegion region;
18     
19     int width;
20     int height;
21         
22     @Override
23     public void create() {
24         // TODO Auto-generated method stub
25         super.create();
26         //TextureRegion region = new TextureRegion( new Texture( Gdx.files.internal( "data/badlogic.jpg" ) ) );
27         region = new TextureRegion( new Texture( Gdx.files.internal( "data/button_green.png" ) ) );
28         patch = new NinePatch( region, 13, 13, 13, 13 );
29         batch = new SpriteBatch();
30         
31         width = 100;
32         height = 30;
33     }
34 
35     @Override
36     public void render() {
37         // TODO Auto-generated method stub
38         super.render();
39         
40         if( Gdx.input.isKeyPressed( Input.Keys.LEFT ) ){
41             width-=2;
42         }
43         else if( Gdx.input.isKeyPressed( Input.Keys.RIGHT ) ){
44             width+=2;
45         }
46         else if( Gdx.input.isKeyPressed( Input.Keys.DOWN ) ){
47             height-=2;
48         }
49         else if( Gdx.input.isKeyPressed( Input.Keys.UP ) ){
50             height+=2;
51         }
52         
53         Gdx.gl.glClearColor( 1, 1, 1, 1 );
54         Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT );
55         
56         batch.begin();
57         patch.draw( batch, 10, 10, width, height );
58         batch.draw( region, 10, 20+height, width, height );
59         batch.end();
60     }
61 
62     @Override
63     public void dispose() {
64         // TODO Auto-generated method stub
65         super.dispose();
66     }
67 
68 }

结果:

上面的是原生态的图片,下面使用了NinePatch,拉伸的时候4个角没有变化,没有出现变形,适合做Button等控件。

原文地址:https://www.cnblogs.com/MiniHouse/p/3835259.html