SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Opengl presentation
Opengl presentationOpengl presentation
Opengl presentationelnaqah
 
Choi JiHyun NDC2011
Choi JiHyun  NDC2011Choi JiHyun  NDC2011
Choi JiHyun NDC2011지현 최
 
[데브루키] Color space gamma correction
[데브루키] Color space gamma correction[데브루키] Color space gamma correction
[데브루키] Color space gamma correctionMinGeun Park
 
Screen Space Decals in Warhammer 40,000: Space Marine
Screen Space Decals in Warhammer 40,000: Space MarineScreen Space Decals in Warhammer 40,000: Space Marine
Screen Space Decals in Warhammer 40,000: Space MarinePope Kim
 
Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails FrameworkPT.JUG
 
Scan line method
Scan line methodScan line method
Scan line methodPooja Dixit
 
Siggraph2016 - The Devil is in the Details: idTech 666
Siggraph2016 - The Devil is in the Details: idTech 666Siggraph2016 - The Devil is in the Details: idTech 666
Siggraph2016 - The Devil is in the Details: idTech 666Tiago Sousa
 
08遺跡景観の分析〜可視領域を調べる〜
08遺跡景観の分析〜可視領域を調べる〜08遺跡景観の分析〜可視領域を調べる〜
08遺跡景観の分析〜可視領域を調べる〜Junpei Ishii
 
How it's made: C++ compilers (GCC)
How it's made: C++ compilers (GCC)How it's made: C++ compilers (GCC)
How it's made: C++ compilers (GCC)Sławomir Zborowski
 
SIGGRAPH 2018 - Full Rays Ahead! From Raster to Real-Time Raytracing
SIGGRAPH 2018 - Full Rays Ahead! From Raster to Real-Time RaytracingSIGGRAPH 2018 - Full Rays Ahead! From Raster to Real-Time Raytracing
SIGGRAPH 2018 - Full Rays Ahead! From Raster to Real-Time RaytracingElectronic Arts / DICE
 
Graphics software
Graphics softwareGraphics software
Graphics softwareMohd Arif
 
NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016Mark Kilgard
 
Parallel Futures of a Game Engine
Parallel Futures of a Game EngineParallel Futures of a Game Engine
Parallel Futures of a Game EngineJohan Andersson
 

Was ist angesagt? (20)

Opengl presentation
Opengl presentationOpengl presentation
Opengl presentation
 
Choi JiHyun NDC2011
Choi JiHyun  NDC2011Choi JiHyun  NDC2011
Choi JiHyun NDC2011
 
[데브루키] Color space gamma correction
[데브루키] Color space gamma correction[데브루키] Color space gamma correction
[데브루키] Color space gamma correction
 
Screen Space Decals in Warhammer 40,000: Space Marine
Screen Space Decals in Warhammer 40,000: Space MarineScreen Space Decals in Warhammer 40,000: Space Marine
Screen Space Decals in Warhammer 40,000: Space Marine
 
Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails Framework
 
Clipping
ClippingClipping
Clipping
 
Scan line method
Scan line methodScan line method
Scan line method
 
Siggraph2016 - The Devil is in the Details: idTech 666
Siggraph2016 - The Devil is in the Details: idTech 666Siggraph2016 - The Devil is in the Details: idTech 666
Siggraph2016 - The Devil is in the Details: idTech 666
 
08遺跡景観の分析〜可視領域を調べる〜
08遺跡景観の分析〜可視領域を調べる〜08遺跡景観の分析〜可視領域を調べる〜
08遺跡景観の分析〜可視領域を調べる〜
 
How it's made: C++ compilers (GCC)
How it's made: C++ compilers (GCC)How it's made: C++ compilers (GCC)
How it's made: C++ compilers (GCC)
 
SIGGRAPH 2018 - Full Rays Ahead! From Raster to Real-Time Raytracing
SIGGRAPH 2018 - Full Rays Ahead! From Raster to Real-Time RaytracingSIGGRAPH 2018 - Full Rays Ahead! From Raster to Real-Time Raytracing
SIGGRAPH 2018 - Full Rays Ahead! From Raster to Real-Time Raytracing
 
visible surface detection
visible surface detectionvisible surface detection
visible surface detection
 
Polygon clipping
Polygon clippingPolygon clipping
Polygon clipping
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
Graphics software
Graphics softwareGraphics software
Graphics software
 
NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016
 
Clipping
ClippingClipping
Clipping
 
OpenVG 1.1 Reference Card
OpenVG 1.1 Reference Card OpenVG 1.1 Reference Card
OpenVG 1.1 Reference Card
 
Entities on Node.JS
Entities on Node.JSEntities on Node.JS
Entities on Node.JS
 
Parallel Futures of a Game Engine
Parallel Futures of a Game EngineParallel Futures of a Game Engine
Parallel Futures of a Game Engine
 

Andere mochten auch

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
 

Andere mochten auch (8)

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)
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Kürzlich hochgeladen (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

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