Android开发之TextView排版问题
2013-12-26 16:50 y-z-f 阅读(6415) 评论(0) 编辑 收藏 举报下面直接是关于解决该问题的代码(根据别人的代码进行了修正以及测试,保证可以修改字体尺寸、颜色、根据padding调整,如果需要支持其他的格式可以将对应的属性添加至Paint类型的对象中):
1 public class NsTextView extends TextView { 2 private String text; 3 private float textSize; 4 private float paddingLeft; 5 private float paddingRight; 6 private int textColor; 7 private Paint paint1 = new Paint(); 8 private float textShowWidth; 9 10 public NsTextView(Context context, AttributeSet attrs) { 11 super(context, attrs); 12 text = this.getText().toString(); 13 textSize = this.getTextSize(); 14 textColor = this.getTextColors().getDefaultColor(); 15 paddingLeft = this.getPaddingLeft(); 16 paddingRight = this.getPaddingRight(); 17 paint1.setTextSize(textSize); 18 paint1.setColor(textColor); 19 paint1.setAntiAlias(true); 20 } 21 22 @Override 23 protected void onDraw(Canvas canvas) { 24 textShowWidth = this.getMeasuredWidth() - paddingLeft - paddingRight; 25 int lineCount = 0; 26 text = this.getText().toString(); 27 if (text == null) 28 return; 29 char[] textCharArray = text.toCharArray(); 30 float drawedWidth = 0; 31 float charWidth; 32 for (int i = 0; i < textCharArray.length; i++) { 33 charWidth = paint1.measureText(textCharArray, i, 1); 34 if (textCharArray[i] == '\n') { 35 lineCount++; 36 drawedWidth = 0; 37 continue; 38 } 39 if (textShowWidth - drawedWidth < charWidth) { 40 lineCount++; 41 drawedWidth = 0; 42 } 43 canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth, 44 (lineCount + 1) * textSize, paint1); 45 drawedWidth += charWidth; 46 } 47 setHeight((int) ((lineCount + 1) * (int) textSize )); 48 } 49 }
Xamarin.Android -> Xamarin.IOS -> 混合 -> Xamarin.Forms
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
2012-12-26 HTML5 基础教程三
2012-12-26 HTML5 基础教程二