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等控件。

posted @   丛林小阁楼  阅读(709)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示