• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.systemui.tv.media.settings;
18 
19 import android.graphics.Canvas;
20 import android.graphics.Paint;
21 import android.graphics.Rect;
22 import android.graphics.drawable.Drawable;
23 import android.text.style.ImageSpan;
24 
25 /** An ImageSpan for a Drawable that is centered vertically in the line. */
26 public class CenteredImageSpan extends ImageSpan {
27 
28     private final Drawable mDrawable;
29 
CenteredImageSpan(Drawable drawable)30     public CenteredImageSpan(Drawable drawable) {
31         super(drawable);
32         mDrawable = drawable;
33     }
34 
35     @Override
getSize( Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fontMetrics)36     public int getSize(
37             Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fontMetrics) {
38         final Rect rect = mDrawable.getBounds();
39 
40         if (fontMetrics != null) {
41             Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
42             int fontHeight = fmPaint.descent - fmPaint.ascent;
43             int drHeight = rect.bottom - rect.top;
44             int centerY = fmPaint.ascent + fontHeight / 2;
45 
46             fontMetrics.ascent = centerY - drHeight / 2;
47             fontMetrics.top = fontMetrics.ascent;
48             fontMetrics.bottom = centerY + drHeight / 2;
49             fontMetrics.descent = fontMetrics.bottom;
50         }
51         return rect.right;
52     }
53 
54     @Override
draw( Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint)55     public void draw(
56             Canvas canvas,
57             CharSequence text,
58             int start,
59             int end,
60             float x,
61             int top,
62             int y,
63             int bottom,
64             Paint paint) {
65         canvas.save();
66         final int transY = (bottom - mDrawable.getBounds().bottom) / 2;
67         canvas.translate(x, transY);
68         mDrawable.draw(canvas);
69         canvas.restore();
70     }
71 }
72