SlideShare una empresa de Scribd logo
1 de 5
Descargar para leer sin conexión
Drawing Text
A brief Android tutorial on drawing text using Canvas.drawText()

Richard Creamer
2to32minus1 (at) gmail (dot) com

Links
Home Page
LinkedIn Profile
Google+ Profile

1
Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved
FontMetrics and Paint.getTextBounds()
• Android provides the android.graphics.Paint.FontMetrics class:
• Provides Typeface dimensions useful for correctly positioning text
• FontMetrics class attributes:
• ascent - “Recommended” distance above baseline
• bottom - Maximum distance below the base line for lowest glyph
• descent - “Recommended” distance below baseline
• leading - “Recommended” space between lines of text
• top - Maximum distance above baseline for tallest glyph
• Important:
• Attribute values pertaining to distances above the baseline are negative
Most Useful
Attributes

baseline

(-) top

Glyph
( bottom - top )

bottom
• Note: Paint.getTextBounds() often provides sufficient information
( FontMetrics object not always needed - see following examples... )

2
Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved
Drawing Text - Code
A general-purpose text drawing method supporting horizontal and vertical alignment
public enum TextVertAlign { Top, Middle, Baseline, Bottom }; // Enumeration representing vertical alignment positions
public static void drawHvAlignedText( Canvas canvas, float x, float y, String s, Paint p, Paint.Align horizAlign, TextVertAlign vertAlign ) {
// Set horizontal alignment
p.setTextAlign( horizAlign );

// Get bounding rectangle which we’ll need below...
Rect r = new Rect();
p.getTextBounds( s, 0, s.length(), r ); // Note: r.top will be negative
// Compute y-coordinate we'll need for drawing text for specified vertical alignment
float textX = x;
float textY = y;
switch ( vertAlign ) {
Also, look at:
case Top:
• Paint.measureText()
textY = y - r.top; // Recall that r.top is negative
• Paint.getFontMetrics()
break;
• android.text.StaticLayout
case Middle:
• android.widget.FrameLayout
textY = y - r.top - r.height()/2;
break;
case Baseline: // Default behavior - no changes to y-coordinate
break;
case Bottom:
textY = y - ( r.height() + r.top );
break;
}
canvas.drawText( s, textX, textY, p ); // Now we can draw the text with the proper ( x, y ) coordinates
}
3
Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved
Text Drawing Example
// Excerpts from TextDrawing demo...
Source code: http://goo.gl/cpq3T
public enum TextVertAlign { Top, Middle, Baseline, Bottom };
private float fontScaleFactor = 0.08f; // Crude scaling to display
private float crosshairScaleFactor = 0.05f; // Crude scaling to display
private int numTextColumns = Paint.Align.values().length;
private int numTextRows = TextVertAlign.values().length;
private float crosshairSize = 10f;
@Override
protected void onDraw( Canvas canvas ) {
canvas.drawPaint( bkgPaint ); // Clear background
// Compute some variables we'll need
float w = getWidth();
float h = getHeight();
crosshairSize = ( w < h ) ? w * crosshairScaleFactor : h * crosshairScaleFactor;
float textSize = ( w < h ) ? w * fontScaleFactor : h * fontScaleFactor;
textPaint.setTextSize( textSize );
float colWidth = ( w - 4 * crosshairSize ) / ( numTextColumns - 1 );
float lineSep = h / ( numTextRows + 1f );
float x = 2f * crosshairSize;

// Loop over horizontal and vertical alignment enum values
// Draw string using loop values for horiz and vert alignment
for ( Paint.Align ha : Paint.Align.values() ) {
float y = lineSep;
for ( TextVertAlign va : TextVertAlign.values() ) {
drawHvAlignedText( canvas, x, y, s, textPaint, ha, va );
drawCrosshairs( canvas, x, y );
y += lineSep;
}
x += colWidth;
}

Left

Center

Right

Top

Middle

Baseline

Bottom

}
Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved

4
Drawing Text
A brief Android tutorial on drawing text using Canvas.drawText()

Richard Creamer
2to32minus1 (at) gmail (dot) com

Links
Home Page
LinkedIn Profile
Google+ Profile

5
Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved

Más contenido relacionado

La actualidad más candente

Hable John Uncharted2 Hdr Lighting
Hable John Uncharted2 Hdr LightingHable John Uncharted2 Hdr Lighting
Hable John Uncharted2 Hdr Lightingozlael ozlael
 
Ndc17 - 차세대 게임이펙트를 위해 알야아할 기법들
Ndc17 - 차세대 게임이펙트를 위해 알야아할 기법들Ndc17 - 차세대 게임이펙트를 위해 알야아할 기법들
Ndc17 - 차세대 게임이펙트를 위해 알야아할 기법들Dae Hyek KIM
 
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019UnityTechnologiesJapan002
 
Terrain in Battlefield 3: A Modern, Complete and Scalable System
Terrain in Battlefield 3: A Modern, Complete and Scalable SystemTerrain in Battlefield 3: A Modern, Complete and Scalable System
Terrain in Battlefield 3: A Modern, Complete and Scalable SystemElectronic Arts / DICE
 
Use Variable Rate Shading (VRS) to Improve the User Experience in Real-Time G...
Use Variable Rate Shading (VRS) to Improve the User Experience in Real-Time G...Use Variable Rate Shading (VRS) to Improve the User Experience in Real-Time G...
Use Variable Rate Shading (VRS) to Improve the User Experience in Real-Time G...Intel® Software
 
More explosions, more chaos, and definitely more blowing stuff up
More explosions, more chaos, and definitely more blowing stuff upMore explosions, more chaos, and definitely more blowing stuff up
More explosions, more chaos, and definitely more blowing stuff upIntel® Software
 
GDC 2014 - Deformable Snow Rendering in Batman: Arkham Origins
GDC 2014 - Deformable Snow Rendering in Batman: Arkham OriginsGDC 2014 - Deformable Snow Rendering in Batman: Arkham Origins
GDC 2014 - Deformable Snow Rendering in Batman: Arkham OriginsColin Barré-Brisebois
 
The Rendering Pipeline - Challenges & Next Steps
The Rendering Pipeline - Challenges & Next StepsThe Rendering Pipeline - Challenges & Next Steps
The Rendering Pipeline - Challenges & Next StepsJohan Andersson
 
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...Unity Technologies
 
Brdf기반 사전정의 스킨 셰이더
Brdf기반 사전정의 스킨 셰이더Brdf기반 사전정의 스킨 셰이더
Brdf기반 사전정의 스킨 셰이더동석 김
 
A Bit More Deferred Cry Engine3
A Bit More Deferred   Cry Engine3A Bit More Deferred   Cry Engine3
A Bit More Deferred Cry Engine3guest11b095
 
Secrets of CryENGINE 3 Graphics Technology
Secrets of CryENGINE 3 Graphics TechnologySecrets of CryENGINE 3 Graphics Technology
Secrets of CryENGINE 3 Graphics TechnologyTiago Sousa
 
Five Rendering Ideas from Battlefield 3 & Need For Speed: The Run
Five Rendering Ideas from Battlefield 3 & Need For Speed: The RunFive Rendering Ideas from Battlefield 3 & Need For Speed: The Run
Five Rendering Ideas from Battlefield 3 & Need For Speed: The RunElectronic Arts / DICE
 
High Dynamic Range color grading and display in Frostbite
High Dynamic Range color grading and display in FrostbiteHigh Dynamic Range color grading and display in Frostbite
High Dynamic Range color grading and display in FrostbiteElectronic Arts / DICE
 
Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Graham Wihlidal
 
Triangle Visibility buffer
Triangle Visibility bufferTriangle Visibility buffer
Triangle Visibility bufferWolfgang Engel
 
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)   A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig) David Salz
 
Unite2019 HLOD를 활용한 대규모 씬 제작 방법
Unite2019 HLOD를 활용한 대규모 씬 제작 방법Unite2019 HLOD를 활용한 대규모 씬 제작 방법
Unite2019 HLOD를 활용한 대규모 씬 제작 방법장규 서
 

La actualidad más candente (20)

Hable John Uncharted2 Hdr Lighting
Hable John Uncharted2 Hdr LightingHable John Uncharted2 Hdr Lighting
Hable John Uncharted2 Hdr Lighting
 
Stochastic Screen-Space Reflections
Stochastic Screen-Space ReflectionsStochastic Screen-Space Reflections
Stochastic Screen-Space Reflections
 
Ndc17 - 차세대 게임이펙트를 위해 알야아할 기법들
Ndc17 - 차세대 게임이펙트를 위해 알야아할 기법들Ndc17 - 차세대 게임이펙트를 위해 알야아할 기법들
Ndc17 - 차세대 게임이펙트를 위해 알야아할 기법들
 
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
 
Terrain in Battlefield 3: A Modern, Complete and Scalable System
Terrain in Battlefield 3: A Modern, Complete and Scalable SystemTerrain in Battlefield 3: A Modern, Complete and Scalable System
Terrain in Battlefield 3: A Modern, Complete and Scalable System
 
Use Variable Rate Shading (VRS) to Improve the User Experience in Real-Time G...
Use Variable Rate Shading (VRS) to Improve the User Experience in Real-Time G...Use Variable Rate Shading (VRS) to Improve the User Experience in Real-Time G...
Use Variable Rate Shading (VRS) to Improve the User Experience in Real-Time G...
 
More explosions, more chaos, and definitely more blowing stuff up
More explosions, more chaos, and definitely more blowing stuff upMore explosions, more chaos, and definitely more blowing stuff up
More explosions, more chaos, and definitely more blowing stuff up
 
GDC 2014 - Deformable Snow Rendering in Batman: Arkham Origins
GDC 2014 - Deformable Snow Rendering in Batman: Arkham OriginsGDC 2014 - Deformable Snow Rendering in Batman: Arkham Origins
GDC 2014 - Deformable Snow Rendering in Batman: Arkham Origins
 
The Rendering Pipeline - Challenges & Next Steps
The Rendering Pipeline - Challenges & Next StepsThe Rendering Pipeline - Challenges & Next Steps
The Rendering Pipeline - Challenges & Next Steps
 
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...
Developing and optimizing a procedural game: The Elder Scrolls Blades- Unite ...
 
Brdf기반 사전정의 스킨 셰이더
Brdf기반 사전정의 스킨 셰이더Brdf기반 사전정의 스킨 셰이더
Brdf기반 사전정의 스킨 셰이더
 
Shiny PC Graphics in Battlefield 3
Shiny PC Graphics in Battlefield 3Shiny PC Graphics in Battlefield 3
Shiny PC Graphics in Battlefield 3
 
A Bit More Deferred Cry Engine3
A Bit More Deferred   Cry Engine3A Bit More Deferred   Cry Engine3
A Bit More Deferred Cry Engine3
 
Secrets of CryENGINE 3 Graphics Technology
Secrets of CryENGINE 3 Graphics TechnologySecrets of CryENGINE 3 Graphics Technology
Secrets of CryENGINE 3 Graphics Technology
 
Five Rendering Ideas from Battlefield 3 & Need For Speed: The Run
Five Rendering Ideas from Battlefield 3 & Need For Speed: The RunFive Rendering Ideas from Battlefield 3 & Need For Speed: The Run
Five Rendering Ideas from Battlefield 3 & Need For Speed: The Run
 
High Dynamic Range color grading and display in Frostbite
High Dynamic Range color grading and display in FrostbiteHigh Dynamic Range color grading and display in Frostbite
High Dynamic Range color grading and display in Frostbite
 
Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016
 
Triangle Visibility buffer
Triangle Visibility bufferTriangle Visibility buffer
Triangle Visibility buffer
 
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)   A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
 
Unite2019 HLOD를 활용한 대규모 씬 제작 방법
Unite2019 HLOD를 활용한 대규모 씬 제작 방법Unite2019 HLOD를 활용한 대규모 씬 제작 방법
Unite2019 HLOD를 활용한 대규모 씬 제작 방법
 

Destacado

Case Study: Cool Clock - An Intro to Android Development
Case Study: Cool Clock - An Intro to Android DevelopmentCase Study: Cool Clock - An Intro to Android Development
Case Study: Cool Clock - An Intro to Android DevelopmentRichard Creamer
 
Introduction to Skia by Ryan Chou @20141008
Introduction to Skia by Ryan Chou @20141008Introduction to Skia by Ryan Chou @20141008
Introduction to Skia by Ryan Chou @20141008Ryan Chou
 
A Detailed Look at Cairo's OpenGL Spans Compositor Performance
A Detailed Look at Cairo's OpenGL Spans Compositor PerformanceA Detailed Look at Cairo's OpenGL Spans Compositor Performance
A Detailed Look at Cairo's OpenGL Spans Compositor PerformanceSamsung Open Source Group
 
The Android graphics path, in depth
The Android graphics path, in depthThe Android graphics path, in depth
The Android graphics path, in depthChris Simmonds
 
Android graphic system (SurfaceFlinger) : Design Pattern's perspective
Android graphic system (SurfaceFlinger) : Design Pattern's perspectiveAndroid graphic system (SurfaceFlinger) : Design Pattern's perspective
Android graphic system (SurfaceFlinger) : Design Pattern's perspectiveBin Chen
 
Android internals 07 - Android graphics (rev_1.1)
Android internals 07 - Android graphics (rev_1.1)Android internals 07 - Android graphics (rev_1.1)
Android internals 07 - Android graphics (rev_1.1)Egor Elizarov
 

Destacado (9)

Case Study: Cool Clock - An Intro to Android Development
Case Study: Cool Clock - An Intro to Android DevelopmentCase Study: Cool Clock - An Intro to Android Development
Case Study: Cool Clock - An Intro to Android Development
 
Duel of Two Libraries: Cairo & Skia
Duel of Two Libraries: Cairo & SkiaDuel of Two Libraries: Cairo & Skia
Duel of Two Libraries: Cairo & Skia
 
Introduction to Skia by Ryan Chou @20141008
Introduction to Skia by Ryan Chou @20141008Introduction to Skia by Ryan Chou @20141008
Introduction to Skia by Ryan Chou @20141008
 
A Detailed Look at Cairo's OpenGL Spans Compositor Performance
A Detailed Look at Cairo's OpenGL Spans Compositor PerformanceA Detailed Look at Cairo's OpenGL Spans Compositor Performance
A Detailed Look at Cairo's OpenGL Spans Compositor Performance
 
The Android graphics path, in depth
The Android graphics path, in depthThe Android graphics path, in depth
The Android graphics path, in depth
 
Android graphic system (SurfaceFlinger) : Design Pattern's perspective
Android graphic system (SurfaceFlinger) : Design Pattern's perspectiveAndroid graphic system (SurfaceFlinger) : Design Pattern's perspective
Android graphic system (SurfaceFlinger) : Design Pattern's perspective
 
Android internals 07 - Android graphics (rev_1.1)
Android internals 07 - Android graphics (rev_1.1)Android internals 07 - Android graphics (rev_1.1)
Android internals 07 - Android graphics (rev_1.1)
 
Hardware Accelerated 2D Rendering for Android
Hardware Accelerated 2D Rendering for AndroidHardware Accelerated 2D Rendering for Android
Hardware Accelerated 2D Rendering for Android
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 

Similar a Precise Android Text Drawing

Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answersdebarghyamukherjee60
 
IT2255 Web Essentials - Unit II Web Designing
IT2255 Web Essentials - Unit II  Web DesigningIT2255 Web Essentials - Unit II  Web Designing
IT2255 Web Essentials - Unit II Web Designingpkaviya
 
R Data Visualization: Learn To Add Text Annotations To Plots
R Data Visualization: Learn To Add Text Annotations To PlotsR Data Visualization: Learn To Add Text Annotations To Plots
R Data Visualization: Learn To Add Text Annotations To PlotsRsquared Academy
 
C programming day#3.
C programming day#3.C programming day#3.
C programming day#3.Mohamed Fawzy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
[1D6]RE-view of Android L developer PRE-view
[1D6]RE-view of Android L developer PRE-view[1D6]RE-view of Android L developer PRE-view
[1D6]RE-view of Android L developer PRE-viewNAVER D2
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.pptUdhayaKumar175069
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in Cummeafruz
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functionsray143eddie
 

Similar a Precise Android Text Drawing (20)

DotNetNuke World CSS3
DotNetNuke World CSS3DotNetNuke World CSS3
DotNetNuke World CSS3
 
c.ppt
c.pptc.ppt
c.ppt
 
HTML-Part2
HTML-Part2HTML-Part2
HTML-Part2
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answers
 
K10947 Vikas ct
K10947 Vikas ctK10947 Vikas ct
K10947 Vikas ct
 
IT2255 Web Essentials - Unit II Web Designing
IT2255 Web Essentials - Unit II  Web DesigningIT2255 Web Essentials - Unit II  Web Designing
IT2255 Web Essentials - Unit II Web Designing
 
R Data Visualization: Learn To Add Text Annotations To Plots
R Data Visualization: Learn To Add Text Annotations To PlotsR Data Visualization: Learn To Add Text Annotations To Plots
R Data Visualization: Learn To Add Text Annotations To Plots
 
WEB DEVELOPMENT
WEB DEVELOPMENTWEB DEVELOPMENT
WEB DEVELOPMENT
 
C programming day#3.
C programming day#3.C programming day#3.
C programming day#3.
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Programming in c
Programming in cProgramming in c
Programming in c
 
An Introduction To Python - Strings & I/O
An Introduction To Python - Strings & I/OAn Introduction To Python - Strings & I/O
An Introduction To Python - Strings & I/O
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
Intake 38 6
Intake 38 6Intake 38 6
Intake 38 6
 
[1D6]RE-view of Android L developer PRE-view
[1D6]RE-view of Android L developer PRE-view[1D6]RE-view of Android L developer PRE-view
[1D6]RE-view of Android L developer PRE-view
 
270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt270_1_CIntro_Up_To_Functions.ppt
270_1_CIntro_Up_To_Functions.ppt
 
Survey of programming language getting started in C
Survey of programming language getting started in CSurvey of programming language getting started in C
Survey of programming language getting started in C
 
270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions270 1 c_intro_up_to_functions
270 1 c_intro_up_to_functions
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Precise Android Text Drawing

  • 1. Drawing Text A brief Android tutorial on drawing text using Canvas.drawText() Richard Creamer 2to32minus1 (at) gmail (dot) com Links Home Page LinkedIn Profile Google+ Profile 1 Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved
  • 2. FontMetrics and Paint.getTextBounds() • Android provides the android.graphics.Paint.FontMetrics class: • Provides Typeface dimensions useful for correctly positioning text • FontMetrics class attributes: • ascent - “Recommended” distance above baseline • bottom - Maximum distance below the base line for lowest glyph • descent - “Recommended” distance below baseline • leading - “Recommended” space between lines of text • top - Maximum distance above baseline for tallest glyph • Important: • Attribute values pertaining to distances above the baseline are negative Most Useful Attributes baseline (-) top Glyph ( bottom - top ) bottom • Note: Paint.getTextBounds() often provides sufficient information ( FontMetrics object not always needed - see following examples... ) 2 Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved
  • 3. Drawing Text - Code A general-purpose text drawing method supporting horizontal and vertical alignment public enum TextVertAlign { Top, Middle, Baseline, Bottom }; // Enumeration representing vertical alignment positions public static void drawHvAlignedText( Canvas canvas, float x, float y, String s, Paint p, Paint.Align horizAlign, TextVertAlign vertAlign ) { // Set horizontal alignment p.setTextAlign( horizAlign ); // Get bounding rectangle which we’ll need below... Rect r = new Rect(); p.getTextBounds( s, 0, s.length(), r ); // Note: r.top will be negative // Compute y-coordinate we'll need for drawing text for specified vertical alignment float textX = x; float textY = y; switch ( vertAlign ) { Also, look at: case Top: • Paint.measureText() textY = y - r.top; // Recall that r.top is negative • Paint.getFontMetrics() break; • android.text.StaticLayout case Middle: • android.widget.FrameLayout textY = y - r.top - r.height()/2; break; case Baseline: // Default behavior - no changes to y-coordinate break; case Bottom: textY = y - ( r.height() + r.top ); break; } canvas.drawText( s, textX, textY, p ); // Now we can draw the text with the proper ( x, y ) coordinates } 3 Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved
  • 4. Text Drawing Example // Excerpts from TextDrawing demo... Source code: http://goo.gl/cpq3T public enum TextVertAlign { Top, Middle, Baseline, Bottom }; private float fontScaleFactor = 0.08f; // Crude scaling to display private float crosshairScaleFactor = 0.05f; // Crude scaling to display private int numTextColumns = Paint.Align.values().length; private int numTextRows = TextVertAlign.values().length; private float crosshairSize = 10f; @Override protected void onDraw( Canvas canvas ) { canvas.drawPaint( bkgPaint ); // Clear background // Compute some variables we'll need float w = getWidth(); float h = getHeight(); crosshairSize = ( w < h ) ? w * crosshairScaleFactor : h * crosshairScaleFactor; float textSize = ( w < h ) ? w * fontScaleFactor : h * fontScaleFactor; textPaint.setTextSize( textSize ); float colWidth = ( w - 4 * crosshairSize ) / ( numTextColumns - 1 ); float lineSep = h / ( numTextRows + 1f ); float x = 2f * crosshairSize; // Loop over horizontal and vertical alignment enum values // Draw string using loop values for horiz and vert alignment for ( Paint.Align ha : Paint.Align.values() ) { float y = lineSep; for ( TextVertAlign va : TextVertAlign.values() ) { drawHvAlignedText( canvas, x, y, s, textPaint, ha, va ); drawCrosshairs( canvas, x, y ); y += lineSep; } x += colWidth; } Left Center Right Top Middle Baseline Bottom } Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved 4
  • 5. Drawing Text A brief Android tutorial on drawing text using Canvas.drawText() Richard Creamer 2to32minus1 (at) gmail (dot) com Links Home Page LinkedIn Profile Google+ Profile 5 Copyright (c) Richard Creamer 2011 - 2012 - All Rights Reserved