Getting started with AndroidLayoutsGradle for AndroidRecyclerView onClickListenersNavigationViewIntentJSON in Android with org.jsonAndroid StudioResourcesData Binding LibraryExceptionsGetting Calculated View DimensionsAsyncTaskSharedPreferencesEmulatorMaterial DesignLint WarningsServiceStoring Files in Internal & External StorageWebViewProject SDK versionsRecyclerViewGoogle Maps API v2 for AndroidPorterDuff Mode9-Patch ImagesAndroid NDKRecyclerView DecorationsCamera 2 APIViewPagerCardViewHttpURLConnectionSQLiteADB (Android Debug Bridge)ButterKnifeSupporting Screens With Different Resolutions, SizesGlideRetrofit2DialogACRAGreenDAOFormatting StringsNotificationsAlarmManagerFragmentsHandlerCreating Custom ViewsBroadcastReceiverActivitySnackbarRuntime Permissions in API-23 +Logging and using LogcatVectorDrawable and AnimatedVectorDrawableTools AttributesToastInterfacesAnimatorsLocationTheme, Style, AttributeThe Manifest FileParcelableMediaPlayerMultidex and the Dex Method LimitData Synchronization with Sync AdapterMenuInstant Run in Android StudioPicassoBluetooth and Bluetooth LE APIRoboGuiceMemory LeaksUniversal Image LoaderVolleyWidgetsDate and Time PickersIntegrate Google Sign InIn-app BillingFloatingActionButtonContentProviderDagger 2RealmUnit testing in Android with JUnitAndroid VersionsWi-Fi ConnectionsSensorManagerLocalization with resources in AndroidProgressBarCustom FontsVibrationGoogle Awareness APIsText to Speech(TTS)UI LifecycleSpinnerData Encryption/DecryptionTesting UI with EspressoWriting UI tests - AndroidGreenRobot EventBusOkHttpEnhancing Android Performance Using Icon FontsHandling Deep LinksCanvas drawing using SurfaceViewFirebaseCrash Reporting ToolsCheck Internet ConnectivityFacebook SDK for AndroidUnzip File in AndroidAndroid Places APICreating your own libraries for Android applicationsGsonDevice Display MetricsTextViewListViewBuilding Backwards Compatible AppsLoaderProGuard - Obfuscating and Shrinking your codeDetect Shake Event in AndroidTypedef Annotations: @IntDef, @StringDefCapturing ScreenshotsMVP ArchitectureOrientation ChangesXposedSecurityPackageManagerImageViewGesture DetectionDoze ModeAndroid Sound and MediaSearchViewCamera and GalleryCallback URLTwitter APIsDrawablesColorsConstraintLayoutRenderScriptFrescoSwipe to RefreshAutoCompleteTextViewInstalling apps with ADBIntentServiceAdMobImplicit IntentsPublish to Play StoreFirebase Realtime DataBaseImage CompressionEmail ValidationKeyboardButtonTextInputLayoutBottom SheetsCoordinatorLayout and BehaviorsEditTextAndroid Paypal Gateway IntegrationFirebase App IndexingFirebase Crash ReportingDisplaying Google AdsAndroid Vk SdkLocalized Date/Time in AndroidCount Down TimerBarcode and QR code readingOtto Event BusTransitionDrawablePort Mapping using Cling library in AndroidCreating Overlay (always-on-top) WindowsExoPlayerInter-app UI testing with UIAutomatorMediaSessionSpeech to Text ConversionFileProviderPublish .aar file to Apache Archiva with GradleXMPP register login and chat simple exampleAndroid AuthenticatorRecyclerView and LayoutManagersAudioManagerJob SchedulingAccounts and AccountManagerIntegrate OpenCV into Android StudioSplit Screen / Multi-Screen ActivitiesThreadMediaStoreTime UtilsTouch EventsFingerprint API in androidMVVM (Architecture)BottomNavigationViewORMLite in androidYoutube-APITabLayoutRetrofit2 with RxJavaDayNight Theme (AppCompat v23.2 / API 14+)ShortcutManagerLruCacheJenkins CI setup for Android ProjectsZip file in androidVector DrawablesfastlaneDefine step value (increment) for custom RangeSeekBarGetting started with OpenGL ES 2.0+Check Data ConnectionAndroid Java Native Interface (JNI)FileIO with AndroidPerformance OptimizationRobolectricMoshiStrict Mode Policy : A tool to catch the bug in the Compile Time.Internationalization and localization (I18N and L10N)Fast way to setup Retrolambda on an android project.How to use SparseArrayFirebase Cloud MessagingShared Element TransitionsAndroid ThingsVideoViewViewFlipperLibrary Dagger 2: Dependency Injection in ApplicationsFormatting phone numbers with pattern.How to store passwords securelyAndroid Kernel OptimizationPaintAudioTrackWhat is ProGuard? What is use in Android?Create Android Custom ROMsJava on AndroidPagination in RecyclerViewGenymotion for androidHandling touch and motion eventsCreating Splash screenConstraintSetCleverTapPublish a library to Maven Repositoriesadb shellPing ICMPAIDLAndroid programming with KotlinAutosizing TextViewsSign your Android App for ReleaseContextActivity RecognitionSecure SharedPreferencesSecure SharedPreferencesBitmap CacheAndroid-x86 in VirtualBoxJCodecDesign PatternsOkioGoogle signin integration on androidTensorFlowAndroid game developmentNotification Channel Android OBluetooth Low EnergyLeakcanaryAdding a FuseView to an Android ProjectAccessing SQLite databases using the ContentValues classEnhancing Alert DialogsHardware Button Events/Intents (PTT, LWP, etc.)SpannableStringLooperOptimized VideoViewGoogle Drive APIAnimated AlertDialog BoxAnnotation ProcessorSyncAdapter with periodically do sync of dataCreate Singleton Class for Toast MessageFastjsonAndroid Architecture ComponentsJacksonGoogle Play StoreLoading Bitmaps EffectivelyGetting system font names and using the fontsSmartcardConvert vietnamese string to english string Android

Paint

Other topics

Creating a Paint

You can create a new paint with one of these 3 constructors:

  • new Paint() Create with default settings
  • new Paint(int flags) Create with flags
  • new Paint(Paint from) Copy settings from another paint

It is generally suggested to never create a paint object, or any other object in onDraw() as it can lead to performance issues. (Android Studio will probably warn you) Instead, make it global and initialize it in your class constructor like so:

public class CustomView extends View {
    
    private Paint paint;
    
    public CustomView(Context context) {
        super(context);
        paint = new Paint();
        //...
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(0xFF000000);
        // ...
    }
}

Setting up Paint for text

Text drawing settings

  • setTypeface(Typeface typeface) Set the font face. See Typeface
  • setTextSize(int size) Set the font size, in pixels.
  • setColor(int color) Set the paint drawing color, including the text color. You can also use setARGB(int a, int r, int g, int b and setAlpha(int alpha)
  • setLetterSpacing(float size) Set the spacing between characters, in ems. Default value is 0, a negative value will tighten the text, while a positive one will expand it.
  • setTextAlign(Paint.Align align) Set text alignment relative to its origin. Paint.Align.LEFT will draw it to the right of the origin, RIGHT will draw it to the left, and CENTER will draw it centered on the origin (horizontally)
  • setTextSkewX(float skewX) This could be considered as fake italic. SkewX represents the horizontal offset of the text bottom. (use -0.25 for italic)
  • setStyle(Paint.Style style) Fill text FILL, Stroke text STROKE, or both FILL_AND_STROKE

Note that you can use TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, size, getResources().getDisplayMetrics()) to convert from SP or DP to pixels.

Measuring text

  • float width = paint.measureText(String text) Measure the width of text
  • float height = paint.ascent() Measure the height of text
  • paint.getTextBounds(String text, int start, int end, Rect bounds Stores the text dimensions. You have allocate the Rect, it cannot be null:
 String text = "Hello world!";
 Rect bounds = new Rect();
 paint.getTextBounds(text, 0, text.length(), bounds);

There are other methods for measuring, however these three should fit most purposes.

Setting up Paint for drawing shapes

  • setStyle(Paint.Style style) Filled shape FILL, Stroke shape STROKE, or both FILL_AND_STROKE
  • setColor(int color) Set the paint drawing color. You can also use setARGB(int a, int r, int g, int b and setAlpha(int alpha)
  • setStrokeCap(Paint.Cap cap) Set line caps, either ROUND, SQUARE, or BUTT (none) See this.
  • setStrokeJoin(Paint.Join join) Set line joins, either MITER (pointy), ROUND, or BEVEL. See this.
  • setStrokeMiter(float miter) Set miter join limit. This can prevent miter join from going on indefinitively, turning it into a bevel join after x pixels. See this.
  • setStrokeWidth(float width) Set stroke width. 0 will draw in hairline mode, independant of the canvas matrix. (always 1 pixel)

Setting flags

You can set the following flags in the constructor, or with setFlags(int flags)

  • Paint.ANTI_ALIAS_FLAG Enable antialiasing, smooths the drawing.
  • Paint.DITHER_FLAG Enable dithering. If color precision is higher than the device's, this will happen.
  • Paint.EMBEDDED_BITMAP_TEXT_FLAG Enables the use of bitmap fonts.
  • Paint.FAKE_BOLD_TEXT_FLAG will draw text with a fake bold effect, can be used instead of using a bold typeface. Some fonts have styled bold, fake bold won't
  • Paint.FILTER_BITMAP_FLAG Affects the sampling of bitmaps when transformed.
  • Paint.HINTING_OFF, Paint.HINTING_ON Toggles font hinting, see this
  • Paint.LINEAR_TEXT_FLAG Disables font scaling, draw operations are scaled instead
  • Paint.SUBPIXEL_TEXT_FLAG Text will be computed using subpixel accuracy.
  • Paint.STRIKE_THRU_TEXT_FLAG Text drawn will be striked
  • Paint.UNDERLINE_TEXT_FLAG Text drawn will be underlined

You can add a flag and remove flags like this:

Paint paint = new Paint();
paint.setFlags(paint.getFlags() | Paint.FLAG);   // Add flag
paint.setFlags(paint.getFlags() & ~Paint.FLAG);  // Remove flag

Trying to remove a flag that isn't there or adding a flag that is already there won't change anything. Also note that most flags can also be set using set<Flag>(boolean enabled), for example setAntialias(true).

You can use paint.reset() to reset the paint to its default settings. The only default flag is EMBEDDED_BITMAP_TEXT_FLAG. It will be set even if you use new Paint(0), you will have

Contributors

Topic Id: 9141

Example Ids: 28376,28377,28378,28379

This site is not affiliated with any of the contributors.