I've been trying to draw a rainbow colored ring in android using the following code:
public void init(){
ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
ringPaint.setStyle(Paint.Style.STROKE);
ringPaint.setStrokeWidth(8f);
ringPaint.setShader(new SweepGradient(0, 0, COLORS2, null));
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(getWidth()/2f,getHeight()/2f ,getHeight()/2f - 16f,ringPaint);
}
the value for COLOR2 is the following:
final int[] COLORS2 = new int[]{Color.parseColor("#33004c"), Color.parseColor("#4600d2"),
Color.parseColor("#0000ff"), Color.parseColor("#0099ff"),
Color.parseColor("#00eeff"),Color.parseColor("#00FF7F"),
Color.parseColor("#48FF00"),Color.parseColor("#B6FF00"),
Color.parseColor("#FFD700"),Color.parseColor("#ff9500"),
Color.parseColor("#FF6200"),Color.parseColor("#FF0000"),
Color.parseColor("#33004c")};
The problem is that I'm only getting a subset of the colors, maybe 3 or 4 of the distinct colors in the array and I'm not entirely sure why, can anyone offer some suggestion as to why this is the case?
you should specify center of view instead of 0,0 when create SweepGradient
look at example please
public class CustomView extends View {
private Paint ringPaint;
public CustomView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public void init() {
ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
ringPaint.setStyle(Paint.Style.STROKE);
ringPaint.setStrokeWidth(8f);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
ringPaint.setShader(new SweepGradient(getWidth() / 2, getHeight() / 2, COLORS2, null));
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(getWidth() / 2f, getHeight() / 2f, getHeight() / 2f - 16f, ringPaint);
}
}
Related
I am trying to draw a circle which will represent time and after each complete circle, I want to change the color to indicate to the user that the next time unit has started and draw over the previous circle color rather than reset as shown in the example below.
I am trying to draw a circle using Draw Arc method in the following way
canvas.drawArc(mRect, 270, sweepAngle, false, fgPaint);
The sweep angle is controlled by an Object Animator :
outerCircleAnimator = ObjectAnimator.ofFloat(timeView, TimeView.SET_SWEEPWANGLE, 0, 360);
With the following code, I am able to achieve the following
The following is my View class :
public class TimeView extends View {
final protected Paint bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
final protected Paint fgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
final protected Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private RectF mRect = new RectF();
private float sweepAngle;
private float radiusInDPI = 100;
private float radiusInPixels;
private float strokeWidthInDPI = 4;
private float stokeWidthInPixels;
private float dpi;
private int heightByTwo;
private int widthByTwo;
public TimeView(Context context) {
super(context);
init();
}
public TimeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TimeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
heightByTwo = h / 2;
widthByTwo = w / 2;
mRect = new RectF(w / 2 - radiusInPixels, h / 2 - radiusInPixels, w / 2 + radiusInPixels, h / 2 + radiusInPixels);
}
private void init() {
DisplayMetrics metrics = getResources().getDisplayMetrics();
dpi = metrics.density;
radiusInPixels = dpi * radiusInDPI;
stokeWidthInPixels = dpi * strokeWidthInDPI;
bgPaint.setStrokeWidth(stokeWidthInPixels);
bgPaint.setStyle(Paint.Style.STROKE);
bgPaint.setColor(ContextCompat.getColor(getContext(), R.color.colorAccent));
fgPaint.setStrokeWidth(stokeWidthInPixels);
fgPaint.setStyle(Paint.Style.STROKE);
fgPaint.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
textPaint.setTextSize(24 * 3);
textPaint.setStyle(Paint.Style.STROKE);
textPaint.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// canvas.drawCircle(widthByTwo, heightByTwo, radiusInPixels, bgPaint);
canvas.drawArc(mRect, 270, sweepAngle, false, fgPaint);
}
public static final Property<TimeView, Float> SET_SWEEPWANGLE =
new Property<TimeView, Float>(Float.class, "outerCircleRadiusProgress") {
#Override
public Float get(TimeView object) {
return object.getSweepAngle();
}
#Override
public void set(TimeView object, Float value) {
object.setSweepAngle(value);
}
};
public float getSweepAngle() {
return sweepAngle;
}
public void setSweepAngle(float sweepAngle) {
Log.v("Testing", "Sweep angle is " + sweepAngle + " " + (sweepAngle + 270));
this.sweepAngle = sweepAngle;
postInvalidate();
}
public void setColor(boolean change) {
if (change) {
fgPaint.setColor(ContextCompat.getColor(getContext(), R.color.mint_green));
} else {
fgPaint.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
}
}
}
onDraw is used to draw on the empty canvas. It is always starting from the beginning. You'll need to save the last fgPaint and:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (lastFgPaint != null) {
canvas.drawArc(mRect, sweepAngle, 360, false, lastFgPaint);
}
canvas.drawArc(mRect, 270, sweepAngle, false, fgPaint);
}
I have little problem with viewPager. I have ViewPager with 4 frgaments which displayed RoundedImageView. The RoundedImageView has a rounded corners. When I was swiped from right to left then a corners is not rounded. That look like this:
I set white rounded backgorund for viewpager. When I not displayed a RoundedImageView(is hide) then all is ok and I have always rounded background in view pager.
I tried set clipChildren and I failed. I don't have idea to resolve my problem.
[EDIT:]
I have another problem with RoundedClipingLayout: W/OpenGLRenderer﹕ Bitmap too large to be uploaded into a texture (1726620832x0, max=4096x4096)
I use this solution. If somebody want to check or use:
public class RoundClippingLinearLayout extends LinearLayout {
private RectF rect;
private int mCornerRadius = 10;
public RoundClippingLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
onInit();
}
public RoundClippingLinearLayout(Context context) {
super(context);
onInit();
}
protected void onInit() {
mCornerRadius = getResources().getDimensionPixelOffset(R.dimen.radius);
setWillNotDraw(false);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw && h != oldh) {
rect = new RectF(0, 0, w, h);
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
canvas.setDrawFilter(new PaintFlagsDrawFilter(1, Paint.ANTI_ALIAS_FLAG));
Path clipPath = new Path();
clipPath.addRoundRect(rect, mCornerRadius, mCornerRadius, Path.Direction.CW);
canvas.clipPath(clipPath);
super.dispatchDraw(canvas);
}
}
I'm trying to achieve a visual effect, that if I could make would look awesome! The login of the app that I'm doing looks like this:
Keep in mind that the image on the background is an animation, that makes a slightly transition from that image to another.
What I want is make the title of the app "Akrasia" be transparent, but transparent meaning that you can see the image in background through the title letters, this means that in some way I must override the onDraw method of the RelativeLayout that contains this form. I tried to do that, but the only thing that I got was errors. Maybe I'm wrong trying to override the onDraw method in boths, the TextView and the RelativeLayout, maybe there's an easiest way to do it. What do you think? Or maybe is impossible to achive this effect?
UPDATE:
This is how it should look like.
Also I tried to make a custom view extending from TextView wich has a method setBackgroundView wich stores a view instance into a field. Later on the onDraw method and I managed to get the bitmap from the background image. But I don't know how draw it using canvas.
UPDATE:
I make it work! Now I only need change that blue-like background by the drawable of the background.
The view:
final public class SeeThroughTextView extends TextView
{
Bitmap mMaskBitmap;
Canvas mMaskCanvas;
Paint mPaint;
Drawable mBackground;
Bitmap mBackgroundBitmap;
Canvas mBackgroundCanvas;
boolean mSetBoundsOnSizeAvailable = false;
public SeeThroughTextView(Context context)
{
super(context);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
}
public SeeThroughTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SeeThroughTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#Override
#Deprecated
public void setBackgroundDrawable(Drawable bg)
{
mBackground = bg;
int w = bg.getIntrinsicWidth();
int h = bg.getIntrinsicHeight();
// Drawable has no dimensions, retrieve View's dimensions
if (w == -1 || h == -1)
{
w = getWidth();
h = getHeight();
}
// Layout has not run
if (w == 0 || h == 0)
{
mSetBoundsOnSizeAvailable = true;
return;
}
mBackground.setBounds(0, 0, w, h);
invalidate();
}
#Override
public void setBackgroundColor(int color)
{
setBackgroundDrawable(new ColorDrawable(color));
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
mBackgroundBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mBackgroundCanvas = new Canvas(mBackgroundBitmap);
mMaskBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mMaskCanvas = new Canvas(mMaskBitmap);
if (mSetBoundsOnSizeAvailable)
{
mBackground.setBounds(0, 0, w, h);
mSetBoundsOnSizeAvailable = false;
}
}
#Override
protected void onDraw(Canvas canvas)
{
// Draw background
mBackground.draw(mBackgroundCanvas);
// Draw mask
mMaskCanvas.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR);
super.onDraw(mMaskCanvas);
mBackgroundCanvas.drawBitmap(mMaskBitmap, 0.f, 0.f, mPaint);
canvas.drawBitmap(mBackgroundBitmap, 0.f, 0.f, null);
}
}
And in my fragment I have this because the animation in the background:
vBackground.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
vTitle.setBackgroundDrawable(new BitmapDrawable(vBackground.getDrawingCache()));
vTitle.invalidate();
}
});
Nailed!
The view:
final public class SeeThroughTextView extends TextView
{
Bitmap mMaskBitmap;
Canvas mMaskCanvas;
Paint mPaint;
Drawable mBackground;
Bitmap mBackgroundBitmap;
Canvas mBackgroundCanvas;
boolean mSetBoundsOnSizeAvailable = false;
public SeeThroughTextView(Context context)
{
super(context);
init();
}
private void init() {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/gillsans.ttf");
setTypeface(myTypeface);
mPaint = new Paint();
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
}
public SeeThroughTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SeeThroughTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#Override
#Deprecated
public void setBackgroundDrawable(Drawable bg)
{
mBackground = bg;
int w = bg.getIntrinsicWidth();
int h = bg.getIntrinsicHeight();
// Drawable has no dimensions, retrieve View's dimensions
if (w == -1 || h == -1)
{
w = getWidth();
h = getHeight();
}
// Layout has not run
if (w == 0 || h == 0)
{
mSetBoundsOnSizeAvailable = true;
return;
}
mBackground.setBounds(0, 0, w, h);
invalidate();
}
#Override
public void setBackgroundColor(int color)
{
setBackgroundDrawable(new ColorDrawable(color));
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
mBackgroundBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mBackgroundCanvas = new Canvas(mBackgroundBitmap);
mMaskBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mMaskCanvas = new Canvas(mMaskBitmap);
if (mSetBoundsOnSizeAvailable)
{
mBackground.setBounds(0, 0, w, h);
mSetBoundsOnSizeAvailable = false;
}
}
#Override
protected void onDraw(Canvas canvas)
{
// Draw background
mBackground.draw(mBackgroundCanvas);
// Draw mask
mMaskCanvas.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR);
super.onDraw(mMaskCanvas);
mBackgroundCanvas.drawBitmap(mMaskBitmap, 0.f, 0.f, mPaint);
canvas.drawBitmap(mBackgroundBitmap, 0.f, 0.f, null);
}
}
In my fragment:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
vLoginBtn = (Button) view.findViewById(R.id.btn_login);
vRegistrationBtn = (Button) view.findViewById(R.id.btn_registration);
vForgotBtn = (Button) view.findViewById(R.id.btn_forgot);
vBackground = (KenBurnsView) view.findViewById(R.id.login_background);
vTitle = (SeeThroughTextView) view.findViewById(R.id.txt_view_login_title);
vBackground.setResourceUrls(
"http://www.youwall.com/papel/peaceful_place_wallpaper_4f3f3.jpg",
"http://www.fwallpaper.net/wallpapers/P/E/Peaceful-Scenary_1920x1200.jpg",
"http://p1.pichost.me/i/39/1620902.jpg"
);
vBackground.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
vTitle.setBackgroundDrawable(getResources().getDrawable(R.drawable.drawable_background_login_top));
vTitle.invalidate();
vBackground.removeOnLayoutChangeListener(this);
}
});
}
The drawables are just two shapes, one with the top-left corner and top-right corner with radius 10dp and the another one with the radius in the bottoms.
The custom TextView with the top drawable shape is alligned above the RelativeLayout wich contains the EditTexts.
No much rocket science. Thanks a lot to #Klotor for suggesting the idea!
Specify a new color in your res/values/colors.xml file (create one if it doesn't exist), the file might look like:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ltGray">#33999999</color>
</resources>
where the first two numbers are transparency (00 - fully transparent, FF - fully opaque).
Then simply set the text color of desired TextView to #color/ltGray in the xml of that layout, or go
tvTitle.setTextColor(getResources().getColor(R.color.ltGray))
after instatiating the TextView.
I have drawn a circle using canvas draw method. Now I want to add a view on circumference of circle. I can get coordinate of circle but totally lost how to add view to that coordinate.
Code is as below -
public class CircleView2 extends LinearLayout {
private int centerX, centerY;
private float fixedRadius = 30;
private Paint paint;
private Logger logger;
private Context context;
TextView textView;
public CircleView2(Context context) {
super(context);
setWillNotDraw(false);
doInit(context);
}
public CircleView2(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
doInit(context);
}
private void doInit(Context context) {
this.context = context;
logger = new Logger(context);
fixedRadius = 30;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.rgb(227, 73, 90));
textView = new TextView(context);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
centerX = w / 2;
centerY = h / 2;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(centerX, centerY, fixedRadius + 160, paint);
double x = centerX + (fixedRadius + 160) * Math.cos(Math.toDegrees(45.0));
double y = centerY + (fixedRadius + 160) * Math.sin(Math.toDegrees(45.0));
logger.debug(x + "");
logger.debug(y + "");
textView.setTextColor(Color.BLACK);
textView.setText("AAA");
textView.draw(canvas);
super.onDraw(canvas);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
This draws circle just fine. But can't add textview. textview.draw(canvas) should add that to view, right ? How to add textview to view and that to at calculated coordinates ?
What I'm doing wrong here?
I am trying to do something very simple (see above). I want all of the pixels of a canvas to be a solid color, except for the the pixels that fill a centered circle. I have read hundreds stack overflow post on this subject and have tried hundreds of things including setting the PorterDuff.Mode. Here is my current onDraw() of MyView extends View:
protected void onDraw(Canvas canvas) {
int w = canvas.getWidth();
int h = canvas.getHeight();
Paint framePaint = new Paint();
framePaint.setStyle(Paint.Style.FILL);
framePaint.setColor(Color.BLUE);
canvas.drawRect(0, 0, w, h, framePaint);
Paint transparentPaint = new Paint();
transparentPaint.setColor(Color.TRANSPARENT);
transparentPaint.setAntiAlias(true);
canvas.drawCircle(w / 2, h / 2, (w + h) / 4, transparentPaint);
}
Am I misunderstanding something, why cant I paint over an existing pixel with transparent paint. When I do this the pixel stays the same. When I use PorterDuff, the pixel turns black. Please help.
Try this:
public class TransparentCircle extends View {
Bitmap bm;
Canvas cv;
Paint eraser;
public TransparentCircle(Context context) {
super(context);
Init();
}
public TransparentCircle(Context context, AttributeSet attrs) {
super(context, attrs);
Init();
}
public TransparentCircle(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
Init();
}
private void Init(){
eraser = new Paint();
eraser.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
eraser.setAntiAlias(true);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw || h != oldh) {
bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
cv = new Canvas(bm);
}
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
int w = getWidth();
int h = getHeight();
int radius = w > h ? h / 2 : w / 2;
bm.eraseColor(Color.TRANSPARENT);
cv.drawColor(Color.BLUE);
cv.drawCircle(w / 2, h / 2, radius, eraser);
canvas.drawBitmap(bm, 0, 0, null);
super.onDraw(canvas);
}
}